diff --git a/.gitignore b/.gitignore index f71e3dc8e..427b8858f 100644 --- a/.gitignore +++ b/.gitignore @@ -177,3 +177,7 @@ artifacts # Temporary typespec folders for typespec generation TempTypeSpecFiles/ + +# Artifacts from the generator +tspCodeModel.json +Configuration.json diff --git a/api/OpenAI.netstandard2.0.cs b/api/OpenAI.netstandard2.0.cs index d696dbe99..b5b587809 100644 --- a/api/OpenAI.netstandard2.0.cs +++ b/api/OpenAI.netstandard2.0.cs @@ -40,11 +40,8 @@ public class Assistant : IJsonModel, IPersistableModel { public float? Temperature { get; } public ToolResources ToolResources { get; } public IReadOnlyList Tools { get; } - Assistant IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - Assistant IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator Assistant(ClientResult result); + public static implicit operator BinaryContent(Assistant assistant); } public class AssistantClient { protected AssistantClient(); @@ -211,8 +208,6 @@ public class AssistantCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct AssistantCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public AssistantCollectionOrder(string value); public static AssistantCollectionOrder Ascending { get; } public static AssistantCollectionOrder Descending { get; } @@ -236,20 +231,14 @@ public class AssistantCreationOptions : IJsonModel, IP public float? Temperature { get; set; } public ToolResources ToolResources { get; set; } public IList Tools { get; } - AssistantCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AssistantCreationOptions(ClientResult result); + public static implicit operator BinaryContent(AssistantCreationOptions assistantCreationOptions); } public class AssistantDeletionResult : IJsonModel, IPersistableModel { public string AssistantId { get; } public bool Deleted { get; } - AssistantDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AssistantDeletionResult(ClientResult result); + public static implicit operator BinaryContent(AssistantDeletionResult assistantDeletionResult); } public class AssistantModificationOptions : IJsonModel, IPersistableModel { public IList DefaultTools { get; } @@ -262,11 +251,8 @@ public class AssistantModificationOptions : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AssistantModificationOptions(ClientResult result); + public static implicit operator BinaryContent(AssistantModificationOptions assistantModificationOptions); } public abstract class AssistantResponseFormat : IEquatable, IEquatable, IJsonModel, IPersistableModel { public static AssistantResponseFormat Auto { get; } @@ -282,15 +268,12 @@ public abstract class AssistantResponseFormat : IEquatable.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); [EditorBrowsable(EditorBrowsableState.Never)] bool IEquatable.Equals(AssistantResponseFormat other); [EditorBrowsable(EditorBrowsableState.Never)] @@ -302,30 +285,23 @@ public class AssistantThread : IJsonModel, IPersistableModel Metadata { get; } public ToolResources ToolResources { get; } - AssistantThread IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantThread IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AssistantThread(ClientResult result); + public static implicit operator BinaryContent(AssistantThread assistantThread); } public class CodeInterpreterToolDefinition : ToolDefinition, IJsonModel, IPersistableModel { - CodeInterpreterToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - CodeInterpreterToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ToolDefinition JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator CodeInterpreterToolDefinition(ClientResult result); + public static implicit operator BinaryContent(CodeInterpreterToolDefinition codeInterpreterToolDefinition); + protected override ToolDefinition PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class CodeInterpreterToolResources : IJsonModel, IPersistableModel { public IList FileIds { get; } - CodeInterpreterToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - CodeInterpreterToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator CodeInterpreterToolResources(ClientResult result); + public static implicit operator BinaryContent(CodeInterpreterToolResources codeInterpreterToolResources); } public readonly partial struct FileSearchRanker : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public FileSearchRanker(string value); public static FileSearchRanker Auto { get; } public static FileSearchRanker Default20240821 { get; } @@ -344,29 +320,24 @@ public class FileSearchRankingOptions : IJsonModel, IP public FileSearchRankingOptions(float scoreThreshold); public FileSearchRanker? Ranker { get; set; } public required float ScoreThreshold { get; set; } - FileSearchRankingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileSearchRankingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator FileSearchRankingOptions(ClientResult result); + public static implicit operator BinaryContent(FileSearchRankingOptions fileSearchRankingOptions); } public class FileSearchToolDefinition : ToolDefinition, IJsonModel, IPersistableModel { public int? MaxResults { get; set; } public FileSearchRankingOptions RankingOptions { get; set; } - FileSearchToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileSearchToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ToolDefinition JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator FileSearchToolDefinition(ClientResult result); + public static implicit operator BinaryContent(FileSearchToolDefinition fileSearchToolDefinition); + protected override ToolDefinition PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class FileSearchToolResources : IJsonModel, IPersistableModel { public IList NewVectorStores { get; } public IList VectorStoreIds { get; } - FileSearchToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileSearchToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator FileSearchToolResources(ClientResult result); + public static implicit operator BinaryContent(FileSearchToolResources fileSearchToolResources); } public class FunctionToolDefinition : ToolDefinition, IJsonModel, IPersistableModel { public FunctionToolDefinition(); @@ -375,11 +346,12 @@ public class FunctionToolDefinition : ToolDefinition, IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FunctionToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ToolDefinition JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator FunctionToolDefinition(ClientResult result); + public static implicit operator BinaryContent(FunctionToolDefinition functionToolDefinition); + protected override ToolDefinition PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class MessageCollectionOptions { public string AfterId { get; set; } @@ -388,8 +360,6 @@ public class MessageCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct MessageCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public MessageCollectionOrder(string value); public static MessageCollectionOrder Ascending { get; } public static MessageCollectionOrder Descending { get; } @@ -413,12 +383,9 @@ public abstract class MessageContent : IJsonModel, IPersistableM public static MessageContent FromImageFileId(string imageFileId, MessageImageDetail? detail = null); public static MessageContent FromImageUri(Uri imageUri, MessageImageDetail? detail = null); public static MessageContent FromText(string text); + public static explicit operator MessageContent(ClientResult result); + public static implicit operator BinaryContent(MessageContent messageContent); public static implicit operator MessageContent(string value); - MessageContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class MessageContentUpdate : StreamingUpdate { public MessageImageDetail? ImageDetail { get; } @@ -434,41 +401,27 @@ public class MessageCreationAttachment : IJsonModel, public MessageCreationAttachment(string fileId, IEnumerable tools); public string FileId { get; } public IReadOnlyList Tools { get; } - MessageCreationAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageCreationAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator MessageCreationAttachment(ClientResult result); + public static implicit operator BinaryContent(MessageCreationAttachment messageCreationAttachment); } public class MessageCreationOptions : IJsonModel, IPersistableModel { public IList Attachments { get; set; } public IDictionary Metadata { get; set; } - MessageCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator MessageCreationOptions(ClientResult result); + public static implicit operator BinaryContent(MessageCreationOptions messageCreationOptions); } public class MessageDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } public string MessageId { get; } - MessageDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator MessageDeletionResult(ClientResult result); + public static implicit operator BinaryContent(MessageDeletionResult messageDeletionResult); } public class MessageFailureDetails : IJsonModel, IPersistableModel { public MessageFailureReason Reason { get; } - MessageFailureDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageFailureDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator MessageFailureDetails(ClientResult result); + public static implicit operator BinaryContent(MessageFailureDetails messageFailureDetails); } public readonly partial struct MessageFailureReason : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public MessageFailureReason(string value); public static MessageFailureReason ContentFilter { get; } public static MessageFailureReason MaxTokens { get; } @@ -492,19 +445,14 @@ public enum MessageImageDetail { } public class MessageModificationOptions : IJsonModel, IPersistableModel { public IDictionary Metadata { get; set; } - MessageModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - MessageModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator MessageModificationOptions(ClientResult result); + public static implicit operator BinaryContent(MessageModificationOptions messageModificationOptions); } public enum MessageRole { User = 0, Assistant = 1 } public readonly partial struct MessageStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public MessageStatus(string value); public static MessageStatus Completed { get; } public static MessageStatus Incomplete { get; } @@ -539,8 +487,6 @@ public class RunCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct RunCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunCollectionOrder(string value); public static RunCollectionOrder Ascending { get; } public static RunCollectionOrder Descending { get; } @@ -569,24 +515,16 @@ public class RunCreationOptions : IJsonModel, IPersistableMo public ToolConstraint ToolConstraint { get; set; } public IList ToolsOverride { get; } public RunTruncationStrategy TruncationStrategy { get; set; } - RunCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunCreationOptions(ClientResult result); + public static implicit operator BinaryContent(RunCreationOptions runCreationOptions); } public class RunError : IJsonModel, IPersistableModel { public RunErrorCode Code { get; } public string Message { get; } - RunError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunError(ClientResult result); + public static implicit operator BinaryContent(RunError runError); } public readonly partial struct RunErrorCode : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunErrorCode(string value); public static RunErrorCode InvalidPrompt { get; } public static RunErrorCode RateLimitExceeded { get; } @@ -603,15 +541,10 @@ public class RunError : IJsonModel, IPersistableModel { } public class RunIncompleteDetails : IJsonModel, IPersistableModel { public RunIncompleteReason? Reason { get; } - RunIncompleteDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunIncompleteDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunIncompleteDetails(ClientResult result); + public static implicit operator BinaryContent(RunIncompleteDetails runIncompleteDetails); } public readonly partial struct RunIncompleteReason : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunIncompleteReason(string value); public static RunIncompleteReason MaxInputTokenCount { get; } public static RunIncompleteReason MaxOutputTokenCount { get; } @@ -627,15 +560,10 @@ public class RunIncompleteDetails : IJsonModel, IPersistab } public class RunModificationOptions : IJsonModel, IPersistableModel { public IDictionary Metadata { get; set; } - RunModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunModificationOptions(ClientResult result); + public static implicit operator BinaryContent(RunModificationOptions runModificationOptions); } public readonly partial struct RunStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunStatus(string value); public static RunStatus Cancelled { get; } public static RunStatus Cancelling { get; } @@ -673,20 +601,14 @@ public class RunStep : IJsonModel, IPersistableModel { public RunStepStatus Status { get; } public string ThreadId { get; } public RunStepTokenUsage Usage { get; } - RunStep IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStep IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStep(ClientResult result); + public static implicit operator BinaryContent(RunStep runStep); } public abstract class RunStepCodeInterpreterOutput : IJsonModel, IPersistableModel { public string ImageFileId { get; } public string Logs { get; } - RunStepCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepCodeInterpreterOutput(ClientResult result); + public static implicit operator BinaryContent(RunStepCodeInterpreterOutput runStepCodeInterpreterOutput); } public class RunStepCollectionOptions { public string AfterId { get; set; } @@ -695,8 +617,6 @@ public class RunStepCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct RunStepCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunStepCollectionOrder(string value); public static RunStepCollectionOrder Ascending { get; } public static RunStepCollectionOrder Descending { get; } @@ -713,11 +633,8 @@ public class RunStepCollectionOptions { public abstract class RunStepDetails : IJsonModel, IPersistableModel { public string CreatedMessageId { get; } public IReadOnlyList ToolCalls { get; } - RunStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepDetails(ClientResult result); + public static implicit operator BinaryContent(RunStepDetails runStepDetails); } public class RunStepDetailsUpdate : StreamingUpdate { public string CodeInterpreterInput { get; } @@ -735,15 +652,10 @@ public class RunStepDetailsUpdate : StreamingUpdate { public class RunStepError : IJsonModel, IPersistableModel { public RunStepErrorCode Code { get; } public string Message { get; } - RunStepError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepError(ClientResult result); + public static implicit operator BinaryContent(RunStepError runStepError); } public readonly partial struct RunStepErrorCode : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunStepErrorCode(string value); public static RunStepErrorCode RateLimitExceeded { get; } public static RunStepErrorCode ServerError { get; } @@ -762,20 +674,14 @@ public class RunStepFileSearchResult : IJsonModel, IPer public string FileId { get; } public string FileName { get; } public float Score { get; } - RunStepFileSearchResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepFileSearchResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepFileSearchResult(ClientResult result); + public static implicit operator BinaryContent(RunStepFileSearchResult runStepFileSearchResult); } public class RunStepFileSearchResultContent : IJsonModel, IPersistableModel { public RunStepFileSearchResultContentKind Kind { get; } public string Text { get; } - RunStepFileSearchResultContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepFileSearchResultContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepFileSearchResultContent(ClientResult result); + public static implicit operator BinaryContent(RunStepFileSearchResultContent runStepFileSearchResultContent); } public enum RunStepFileSearchResultContentKind { Text = 0 @@ -785,8 +691,6 @@ public enum RunStepKind { ToolCall = 1 } public readonly partial struct RunStepStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public RunStepStatus(string value); public static RunStepStatus Cancelled { get; } public static RunStepStatus Completed { get; } @@ -807,11 +711,8 @@ public class RunStepTokenUsage : IJsonModel, IPersistableMode public int InputTokenCount { get; } public int OutputTokenCount { get; } public int TotalTokenCount { get; } - RunStepTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepTokenUsage(ClientResult result); + public static implicit operator BinaryContent(RunStepTokenUsage runStepTokenUsage); } public abstract class RunStepToolCall : IJsonModel, IPersistableModel { public string CodeInterpreterInput { get; } @@ -823,11 +724,8 @@ public abstract class RunStepToolCall : IJsonModel, IPersistabl public string FunctionOutput { get; } public string Id { get; } public RunStepToolCallKind Kind { get; } - RunStepToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepToolCall(ClientResult result); + public static implicit operator BinaryContent(RunStepToolCall runStepToolCall); } public enum RunStepToolCallKind { CodeInterpreter = 0, @@ -840,31 +738,22 @@ public abstract class RunStepUpdateCodeInterpreterOutput : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunStepUpdateCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunStepUpdateCodeInterpreterOutput(ClientResult result); + public static implicit operator BinaryContent(RunStepUpdateCodeInterpreterOutput runStepUpdateCodeInterpreterOutput); } public class RunTokenUsage : IJsonModel, IPersistableModel { public int InputTokenCount { get; } public int OutputTokenCount { get; } public int TotalTokenCount { get; } - RunTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunTokenUsage(ClientResult result); + public static implicit operator BinaryContent(RunTokenUsage runTokenUsage); } public class RunTruncationStrategy : IJsonModel, IPersistableModel { public static RunTruncationStrategy Auto { get; } public int? LastMessages { get; } public static RunTruncationStrategy CreateLastMessagesStrategy(int lastMessageCount); - RunTruncationStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - RunTruncationStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator RunTruncationStrategy(ClientResult result); + public static implicit operator BinaryContent(RunTruncationStrategy runTruncationStrategy); } public class RunUpdate : StreamingUpdate { } @@ -922,20 +811,14 @@ public class ThreadCreationOptions : IJsonModel, IPersist public IList InitialMessages { get; } public IDictionary Metadata { get; set; } public ToolResources ToolResources { get; set; } - ThreadCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ThreadCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ThreadCreationOptions(ClientResult result); + public static implicit operator BinaryContent(ThreadCreationOptions threadCreationOptions); } public class ThreadDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } public string ThreadId { get; } - ThreadDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ThreadDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ThreadDeletionResult(ClientResult result); + public static implicit operator BinaryContent(ThreadDeletionResult threadDeletionResult); } public class ThreadInitializationMessage : MessageCreationOptions { public ThreadInitializationMessage(MessageRole role, IEnumerable content); @@ -955,20 +838,14 @@ public class ThreadMessage : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ThreadMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ThreadMessage(ClientResult result); + public static implicit operator BinaryContent(ThreadMessage threadMessage); } public class ThreadModificationOptions : IJsonModel, IPersistableModel { public IDictionary Metadata { get; set; } public ToolResources ToolResources { get; set; } - ThreadModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ThreadModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ThreadModificationOptions(ClientResult result); + public static implicit operator BinaryContent(ThreadModificationOptions threadModificationOptions); } public class ThreadRun : IJsonModel, IPersistableModel { public bool? AllowParallelToolCalls { get; } @@ -997,11 +874,8 @@ public class ThreadRun : IJsonModel, IPersistableModel { public IReadOnlyList Tools { get; } public RunTruncationStrategy TruncationStrategy { get; } public RunTokenUsage Usage { get; } - ThreadRun IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ThreadRun IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ThreadRun(ClientResult result); + public static implicit operator BinaryContent(ThreadRun threadRun); } public class ThreadUpdate : StreamingUpdate { public DateTimeOffset CreatedAt { get; } @@ -1014,11 +888,8 @@ public class ToolConstraint : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ToolConstraint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ToolConstraint(ClientResult result); + public static implicit operator BinaryContent(ToolConstraint toolConstraint); } public abstract class ToolDefinition : IJsonModel, IPersistableModel { protected ToolDefinition(); @@ -1026,31 +897,22 @@ public abstract class ToolDefinition : IJsonModel, IPersistableM public static CodeInterpreterToolDefinition CreateCodeInterpreter(); public static FileSearchToolDefinition CreateFileSearch(int? maxResults = null); public static FunctionToolDefinition CreateFunction(string name, string description = null, BinaryData parameters = null, bool? strictParameterSchemaEnabled = null); - ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ToolDefinition(ClientResult result); + public static implicit operator BinaryContent(ToolDefinition toolDefinition); } public class ToolOutput : IJsonModel, IPersistableModel { public ToolOutput(); public ToolOutput(string toolCallId, string output); public string Output { get; set; } public string ToolCallId { get; set; } - ToolOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ToolOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ToolOutput(ClientResult result); + public static implicit operator BinaryContent(ToolOutput toolOutput); } public class ToolResources : IJsonModel, IPersistableModel { public CodeInterpreterToolResources CodeInterpreter { get; set; } public FileSearchToolResources FileSearch { get; set; } - ToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ToolResources(ClientResult result); + public static implicit operator BinaryContent(ToolResources toolResources); } public class VectorStoreCreationHelper : IJsonModel, IPersistableModel { public VectorStoreCreationHelper(); @@ -1059,11 +921,8 @@ public class VectorStoreCreationHelper : IJsonModel, public FileChunkingStrategy ChunkingStrategy { get; set; } public IList FileIds { get; } public IDictionary Metadata { get; } - VectorStoreCreationHelper IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreCreationHelper IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreCreationHelper(ClientResult result); + public static implicit operator BinaryContent(VectorStoreCreationHelper vectorStoreCreationHelper); } } namespace OpenAI.Audio { @@ -1107,15 +966,10 @@ public class AudioTranscription : IJsonModel, IPersistableMo public IReadOnlyList Segments { get; } public string Text { get; } public IReadOnlyList Words { get; } - AudioTranscription IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AudioTranscription IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AudioTranscription(ClientResult result); + public static implicit operator BinaryContent(AudioTranscription audioTranscription); } public readonly partial struct AudioTranscriptionFormat : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public AudioTranscriptionFormat(string value); public static AudioTranscriptionFormat Simple { get; } public static AudioTranscriptionFormat Srt { get; } @@ -1139,26 +993,18 @@ public class AudioTranscriptionOptions : IJsonModel, public AudioTranscriptionFormat? ResponseFormat { get; set; } public float? Temperature { get; set; } public AudioTimestampGranularities TimestampGranularities { get; set; } - AudioTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AudioTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AudioTranscriptionOptions(ClientResult result); + public static implicit operator BinaryContent(AudioTranscriptionOptions audioTranscriptionOptions); } public class AudioTranslation : IJsonModel, IPersistableModel { public TimeSpan? Duration { get; } public string Language { get; } public IReadOnlyList Segments { get; } public string Text { get; } - AudioTranslation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AudioTranslation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AudioTranslation(ClientResult result); + public static implicit operator BinaryContent(AudioTranslation audioTranslation); } public readonly partial struct AudioTranslationFormat : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public AudioTranslationFormat(string value); public static AudioTranslationFormat Simple { get; } public static AudioTranslationFormat Srt { get; } @@ -1180,15 +1026,10 @@ public class AudioTranslationOptions : IJsonModel, IPer public string Prompt { get; set; } public AudioTranslationFormat? ResponseFormat { get; set; } public float? Temperature { get; set; } - AudioTranslationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AudioTranslationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator AudioTranslationOptions(ClientResult result); + public static implicit operator BinaryContent(AudioTranslationOptions audioTranslationOptions); } public readonly partial struct GeneratedSpeechFormat : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public GeneratedSpeechFormat(string value); public static GeneratedSpeechFormat Aac { get; } public static GeneratedSpeechFormat Flac { get; } @@ -1207,8 +1048,6 @@ public class AudioTranslationOptions : IJsonModel, IPer public override readonly string ToString(); } public readonly partial struct GeneratedSpeechVoice : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public GeneratedSpeechVoice(string value); public static GeneratedSpeechVoice Alloy { get; } public static GeneratedSpeechVoice Echo { get; } @@ -1235,15 +1074,10 @@ public static class OpenAIAudioModelFactory { public class SpeechGenerationOptions : IJsonModel, IPersistableModel { public GeneratedSpeechFormat? ResponseFormat { get; set; } public float? SpeedRatio { get; set; } - SpeechGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - SpeechGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator SpeechGenerationOptions(ClientResult result); + public static implicit operator BinaryContent(SpeechGenerationOptions speechGenerationOptions); } public readonly partial struct TranscribedSegment : IJsonModel, IPersistableModel, IJsonModel, IPersistableModel { - private readonly object _dummy; - private readonly int _dummyPrimitive; public float AverageLogProbability { get; } public float CompressionRatio { get; } public TimeSpan EndTime { get; } @@ -1254,33 +1088,15 @@ public class SpeechGenerationOptions : IJsonModel, IPer public float Temperature { get; } public string Text { get; } public ReadOnlyMemory TokenIds { get; } - readonly TranscribedSegment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - readonly void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - readonly object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - readonly void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - readonly TranscribedSegment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - readonly string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - readonly BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - readonly object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - readonly string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - readonly BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator TranscribedSegment(ClientResult result); + public static implicit operator BinaryContent(TranscribedSegment transcribedSegment); } public readonly partial struct TranscribedWord : IJsonModel, IPersistableModel, IJsonModel, IPersistableModel { - private readonly object _dummy; - private readonly int _dummyPrimitive; public TimeSpan EndTime { get; } public TimeSpan StartTime { get; } public string Word { get; } - readonly TranscribedWord IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - readonly void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - readonly object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - readonly void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - readonly TranscribedWord IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - readonly string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - readonly BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - readonly object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - readonly string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - readonly BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator TranscribedWord(ClientResult result); + public static implicit operator BinaryContent(TranscribedWord transcribedWord); } } namespace OpenAI.Batch { @@ -1323,11 +1139,12 @@ public class AssistantChatMessage : ChatMessage, IJsonModel ToolCalls { get; } - AssistantChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - AssistantChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator AssistantChatMessage(ClientResult result); + public static implicit operator BinaryContent(AssistantChatMessage assistantChatMessage); + protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ChatClient { protected ChatClient(); @@ -1364,11 +1181,8 @@ public class ChatCompletion : IJsonModel, IPersistableModel ToolCalls { get; } public ChatTokenUsage Usage { get; } - ChatCompletion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatCompletion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatCompletion(ClientResult result); + public static implicit operator BinaryContent(ChatCompletion chatCompletion); } public class ChatCompletionOptions : IJsonModel, IPersistableModel { public bool? AllowParallelToolCalls { get; set; } @@ -1392,11 +1206,8 @@ public class ChatCompletionOptions : IJsonModel, IPersist public IList Tools { get; } public int? TopLogProbabilityCount { get; set; } public float? TopP { get; set; } - ChatCompletionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatCompletionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatCompletionOptions(ClientResult result); + public static implicit operator BinaryContent(ChatCompletionOptions chatCompletionOptions); } public enum ChatFinishReason { Stop = 0, @@ -1411,37 +1222,26 @@ public class ChatFunction : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatFunction(ClientResult result); + public static implicit operator BinaryContent(ChatFunction chatFunction); } [Obsolete("This class is obsolete. Please use ChatToolCall instead.")] public class ChatFunctionCall : IJsonModel, IPersistableModel { public ChatFunctionCall(string functionName, BinaryData functionArguments); public BinaryData FunctionArguments { get; } public string FunctionName { get; } - ChatFunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatFunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatFunctionCall(ClientResult result); + public static implicit operator BinaryContent(ChatFunctionCall chatFunctionCall); } [Obsolete("This class is obsolete. Please use ChatToolChoice instead.")] public class ChatFunctionChoice : IJsonModel, IPersistableModel { public static ChatFunctionChoice CreateAutoChoice(); public static ChatFunctionChoice CreateNamedChoice(string functionName); public static ChatFunctionChoice CreateNoneChoice(); - ChatFunctionChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatFunctionChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatFunctionChoice(ClientResult result); + public static implicit operator BinaryContent(ChatFunctionChoice chatFunctionChoice); } public readonly partial struct ChatImageDetailLevel : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ChatImageDetailLevel(string value); public static ChatImageDetailLevel Auto { get; } public static ChatImageDetailLevel High { get; } @@ -1459,11 +1259,8 @@ public class ChatFunctionChoice : IJsonModel, IPersistableMo public class ChatInputTokenUsageDetails : IJsonModel, IPersistableModel { public int AudioTokenCount { get; } public int CachedTokenCount { get; } - ChatInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatInputTokenUsageDetails(ClientResult result); + public static implicit operator BinaryContent(ChatInputTokenUsageDetails chatInputTokenUsageDetails); } public class ChatMessage : IJsonModel, IPersistableModel { public ChatMessageContent Content { get; } @@ -1484,12 +1281,9 @@ public class ChatMessage : IJsonModel, IPersistableModel contentParts); public static UserChatMessage CreateUserMessage(string content); + public static explicit operator ChatMessage(ClientResult result); + public static implicit operator BinaryContent(ChatMessage chatMessage); public static implicit operator ChatMessage(string content); - ChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class ChatMessageContent : ObjectModel.Collection { public ChatMessageContent(); @@ -1509,12 +1303,9 @@ public class ChatMessageContentPart : IJsonModel, IPersi public static ChatMessageContentPart CreateImagePart(Uri imageUri, ChatImageDetailLevel? imageDetailLevel = null); public static ChatMessageContentPart CreateRefusalPart(string refusal); public static ChatMessageContentPart CreateTextPart(string text); + public static explicit operator ChatMessageContentPart(ClientResult result); + public static implicit operator BinaryContent(ChatMessageContentPart chatMessageContentPart); public static implicit operator ChatMessageContentPart(string text); - ChatMessageContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatMessageContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public enum ChatMessageContentPartKind { Text = 0, @@ -1531,42 +1322,30 @@ public enum ChatMessageRole { public class ChatOutputTokenUsageDetails : IJsonModel, IPersistableModel { public int AudioTokenCount { get; } public int ReasoningTokenCount { get; } - ChatOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatOutputTokenUsageDetails(ClientResult result); + public static implicit operator BinaryContent(ChatOutputTokenUsageDetails chatOutputTokenUsageDetails); } public class ChatResponseFormat : IJsonModel, IPersistableModel { public static ChatResponseFormat CreateJsonObjectFormat(); public static ChatResponseFormat CreateJsonSchemaFormat(string jsonSchemaFormatName, BinaryData jsonSchema, string jsonSchemaFormatDescription = null, bool? jsonSchemaIsStrict = null); public static ChatResponseFormat CreateTextFormat(); - ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatResponseFormat(ClientResult result); + public static implicit operator BinaryContent(ChatResponseFormat chatResponseFormat); } public class ChatTokenLogProbabilityDetails : IJsonModel, IPersistableModel { public float LogProbability { get; } public string Token { get; } public IReadOnlyList TopLogProbabilities { get; } public ReadOnlyMemory? Utf8Bytes { get; } - ChatTokenLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatTokenLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatTokenLogProbabilityDetails(ClientResult result); + public static implicit operator BinaryContent(ChatTokenLogProbabilityDetails chatTokenLogProbabilityDetails); } public class ChatTokenTopLogProbabilityDetails : IJsonModel, IPersistableModel { public float LogProbability { get; } public string Token { get; } public ReadOnlyMemory? Utf8Bytes { get; } - ChatTokenTopLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatTokenTopLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatTokenTopLogProbabilityDetails(ClientResult result); + public static implicit operator BinaryContent(ChatTokenTopLogProbabilityDetails chatTokenTopLogProbabilityDetails); } public class ChatTokenUsage : IJsonModel, IPersistableModel { public int InputTokenCount { get; } @@ -1574,11 +1353,8 @@ public class ChatTokenUsage : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatTokenUsage(ClientResult result); + public static implicit operator BinaryContent(ChatTokenUsage chatTokenUsage); } public class ChatTool : IJsonModel, IPersistableModel { public string FunctionDescription { get; } @@ -1587,11 +1363,8 @@ public class ChatTool : IJsonModel, IPersistableModel { public bool? FunctionSchemaIsStrict { get; } public ChatToolKind Kind { get; } public static ChatTool CreateFunctionTool(string functionName, string functionDescription = null, BinaryData functionParameters = null, bool? functionSchemaIsStrict = null); - ChatTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatTool(ClientResult result); + public static implicit operator BinaryContent(ChatTool chatTool); } public class ChatToolCall : IJsonModel, IPersistableModel { public BinaryData FunctionArguments { get; } @@ -1599,11 +1372,8 @@ public class ChatToolCall : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatToolCall(ClientResult result); + public static implicit operator BinaryContent(ChatToolCall chatToolCall); } public enum ChatToolCallKind { Function = 0 @@ -1613,11 +1383,8 @@ public class ChatToolChoice : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ChatToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ChatToolChoice(ClientResult result); + public static implicit operator BinaryContent(ChatToolChoice chatToolChoice); } public enum ChatToolKind { Function = 0 @@ -1626,11 +1393,12 @@ public enum ChatToolKind { public class FunctionChatMessage : ChatMessage, IJsonModel, IPersistableModel { public FunctionChatMessage(string functionName, string content); public string FunctionName { get; } - FunctionChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FunctionChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator FunctionChatMessage(ClientResult result); + public static implicit operator BinaryContent(FunctionChatMessage functionChatMessage); + protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public static class OpenAIChatModelFactory { public static ChatCompletion ChatCompletion(string id = null, ChatFinishReason finishReason = ChatFinishReason.Stop, ChatMessageContent content = null, string refusal = null, IEnumerable toolCalls = null, ChatMessageRole role = ChatMessageRole.System, ChatFunctionCall functionCall = null, IEnumerable contentTokenLogProbabilities = null, IEnumerable refusalTokenLogProbabilities = null, DateTimeOffset createdAt = default, string model = null, string systemFingerprint = null, ChatTokenUsage usage = null); @@ -1659,21 +1427,15 @@ public class StreamingChatCompletionUpdate : IJsonModel ToolCallUpdates { get; } public ChatTokenUsage Usage { get; } - StreamingChatCompletionUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - StreamingChatCompletionUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator StreamingChatCompletionUpdate(ClientResult result); + public static implicit operator BinaryContent(StreamingChatCompletionUpdate streamingChatCompletionUpdate); } [Obsolete("This class is obsolete. Please use StreamingChatToolCallUpdate instead.")] public class StreamingChatFunctionCallUpdate : IJsonModel, IPersistableModel { public BinaryData FunctionArgumentsUpdate { get; } public string FunctionName { get; } - StreamingChatFunctionCallUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - StreamingChatFunctionCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator StreamingChatFunctionCallUpdate(ClientResult result); + public static implicit operator BinaryContent(StreamingChatFunctionCallUpdate streamingChatFunctionCallUpdate); } public class StreamingChatToolCallUpdate : IJsonModel, IPersistableModel { public BinaryData FunctionArgumentsUpdate { get; } @@ -1681,44 +1443,44 @@ public class StreamingChatToolCallUpdate : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - StreamingChatToolCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator StreamingChatToolCallUpdate(ClientResult result); + public static implicit operator BinaryContent(StreamingChatToolCallUpdate streamingChatToolCallUpdate); } public class SystemChatMessage : ChatMessage, IJsonModel, IPersistableModel { public SystemChatMessage(params ChatMessageContentPart[] contentParts); public SystemChatMessage(IEnumerable contentParts); public SystemChatMessage(string content); public string ParticipantName { get; set; } - SystemChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - SystemChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator SystemChatMessage(ClientResult result); + public static implicit operator BinaryContent(SystemChatMessage systemChatMessage); + protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ToolChatMessage : ChatMessage, IJsonModel, IPersistableModel { public ToolChatMessage(string toolCallId, params ChatMessageContentPart[] contentParts); public ToolChatMessage(string toolCallId, IEnumerable contentParts); public ToolChatMessage(string toolCallId, string content); public string ToolCallId { get; } - ToolChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ToolChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ToolChatMessage(ClientResult result); + public static implicit operator BinaryContent(ToolChatMessage toolChatMessage); + protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class UserChatMessage : ChatMessage, IJsonModel, IPersistableModel { public UserChatMessage(params ChatMessageContentPart[] contentParts); public UserChatMessage(IEnumerable contentParts); public UserChatMessage(string content); public string ParticipantName { get; set; } - UserChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - UserChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator UserChatMessage(ClientResult result); + public static implicit operator BinaryContent(UserChatMessage userChatMessage); + protected override ChatMessage PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } } namespace OpenAI.Embeddings { @@ -1743,38 +1505,26 @@ public class EmbeddingClient { public class EmbeddingGenerationOptions : IJsonModel, IPersistableModel { public int? Dimensions { get; set; } public string EndUserId { get; set; } - EmbeddingGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - EmbeddingGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator EmbeddingGenerationOptions(ClientResult result); + public static implicit operator BinaryContent(EmbeddingGenerationOptions embeddingGenerationOptions); } public class EmbeddingTokenUsage : IJsonModel, IPersistableModel { public int InputTokenCount { get; } public int TotalTokenCount { get; } - EmbeddingTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - EmbeddingTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator EmbeddingTokenUsage(ClientResult result); + public static implicit operator BinaryContent(EmbeddingTokenUsage embeddingTokenUsage); } public class OpenAIEmbedding : IJsonModel, IPersistableModel { public int Index { get; } - OpenAIEmbedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIEmbedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIEmbedding(ClientResult result); + public static implicit operator BinaryContent(OpenAIEmbedding openAIEmbedding); public ReadOnlyMemory ToFloats(); } public class OpenAIEmbeddingCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { public string Model { get; } public EmbeddingTokenUsage Usage { get; } - OpenAIEmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIEmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIEmbeddingCollection(ClientResult result); + public static implicit operator BinaryContent(OpenAIEmbeddingCollection openAIEmbeddingCollection); } public static class OpenAIEmbeddingsModelFactory { public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokenCount = 0, int totalTokenCount = 0); @@ -1786,11 +1536,8 @@ namespace OpenAI.Files { public class FileDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } public string FileId { get; } - FileDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator FileDeletionResult(ClientResult result); + public static implicit operator BinaryContent(FileDeletionResult fileDeletionResult); } public enum FilePurpose { Assistants = 0, @@ -1808,8 +1555,6 @@ public enum FileStatus { Error = 2 } public readonly partial struct FileUploadPurpose : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public FileUploadPurpose(string value); public static FileUploadPurpose Assistants { get; } public static FileUploadPurpose Batch { get; } @@ -1835,11 +1580,8 @@ public class OpenAIFile : IJsonModel, IPersistableModel public FileStatus Status { get; } [Obsolete("This property is obsolete. For details on why a fine-tuning training file failed validation, see the `error` field on the fine-tuning job.")] public string StatusDetails { get; } - OpenAIFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIFile(ClientResult result); + public static implicit operator BinaryContent(OpenAIFile openAIFile); } public class OpenAIFileClient { protected OpenAIFileClient(); @@ -1894,11 +1636,8 @@ public class OpenAIFileClient { public virtual Task> UploadFileAsync(string filePath, FileUploadPurpose purpose); } public class OpenAIFileCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - OpenAIFileCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIFileCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIFileCollection(ClientResult result); + public static implicit operator BinaryContent(OpenAIFileCollection openAIFileCollection); } public static class OpenAIFilesModelFactory { public static FileDeletionResult FileDeletionResult(string fileId = null, bool deleted = false); @@ -1945,23 +1684,15 @@ public class GeneratedImage : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - GeneratedImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator GeneratedImage(ClientResult result); + public static implicit operator BinaryContent(GeneratedImage generatedImage); } public class GeneratedImageCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { public DateTimeOffset CreatedAt { get; } - GeneratedImageCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - GeneratedImageCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator GeneratedImageCollection(ClientResult result); + public static implicit operator BinaryContent(GeneratedImageCollection generatedImageCollection); } public readonly partial struct GeneratedImageFormat : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public GeneratedImageFormat(string value); public static GeneratedImageFormat Bytes { get; } public static GeneratedImageFormat Uri { get; } @@ -1976,8 +1707,6 @@ public class GeneratedImageCollection : ObjectModel.ReadOnlyCollection { - private readonly object _dummy; - private readonly int _dummyPrimitive; public GeneratedImageQuality(string value); public static GeneratedImageQuality High { get; } public static GeneratedImageQuality Standard { get; } @@ -1992,8 +1721,6 @@ public class GeneratedImageCollection : ObjectModel.ReadOnlyCollection { - private readonly object _dummy; - private readonly int _dummyPrimitive; public static readonly GeneratedImageSize W1024xH1024; public static readonly GeneratedImageSize W1024xH1792; public static readonly GeneratedImageSize W1792xH1024; @@ -2010,8 +1737,6 @@ public class GeneratedImageCollection : ObjectModel.ReadOnlyCollection { - private readonly object _dummy; - private readonly int _dummyPrimitive; public GeneratedImageStyle(string value); public static GeneratedImageStyle Natural { get; } public static GeneratedImageStyle Vivid { get; } @@ -2077,11 +1802,8 @@ public class ImageEditOptions : IJsonModel, IPersistableModel< public string EndUserId { get; set; } public GeneratedImageFormat? ResponseFormat { get; set; } public GeneratedImageSize? Size { get; set; } - ImageEditOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ImageEditOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ImageEditOptions(ClientResult result); + public static implicit operator BinaryContent(ImageEditOptions imageEditOptions); } public class ImageGenerationOptions : IJsonModel, IPersistableModel { public string EndUserId { get; set; } @@ -2089,21 +1811,15 @@ public class ImageGenerationOptions : IJsonModel, IPersi public GeneratedImageFormat? ResponseFormat { get; set; } public GeneratedImageSize? Size { get; set; } public GeneratedImageStyle? Style { get; set; } - ImageGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ImageGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ImageGenerationOptions(ClientResult result); + public static implicit operator BinaryContent(ImageGenerationOptions imageGenerationOptions); } public class ImageVariationOptions : IJsonModel, IPersistableModel { public string EndUserId { get; set; } public GeneratedImageFormat? ResponseFormat { get; set; } public GeneratedImageSize? Size { get; set; } - ImageVariationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ImageVariationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ImageVariationOptions(ClientResult result); + public static implicit operator BinaryContent(ImageVariationOptions imageVariationOptions); } public static class OpenAIImagesModelFactory { public static GeneratedImage GeneratedImage(BinaryData imageBytes = null, Uri imageUri = null, string revisedPrompt = null); @@ -2114,21 +1830,15 @@ namespace OpenAI.Models { public class ModelDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } public string ModelId { get; } - ModelDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModelDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ModelDeletionResult(ClientResult result); + public static implicit operator BinaryContent(ModelDeletionResult modelDeletionResult); } public class OpenAIModel : IJsonModel, IPersistableModel { public DateTimeOffset CreatedAt { get; } public string Id { get; } public string OwnedBy { get; } - OpenAIModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIModel(ClientResult result); + public static implicit operator BinaryContent(OpenAIModel openAIModel); } public class OpenAIModelClient { protected OpenAIModelClient(); @@ -2157,11 +1867,8 @@ public class OpenAIModelClient { public virtual Task> GetModelsAsync(CancellationToken cancellationToken = default); } public class OpenAIModelCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - OpenAIModelCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIModelCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator OpenAIModelCollection(ClientResult result); + public static implicit operator BinaryContent(OpenAIModelCollection openAIModelCollection); } public static class OpenAIModelsModelFactory { public static ModelDeletionResult ModelDeletionResult(string modelId = null, bool deleted = false); @@ -2205,20 +1912,14 @@ public class ModerationResult : IJsonModel, IPersistableModel< public ModerationCategory SexualMinors { get; } public ModerationCategory Violence { get; } public ModerationCategory ViolenceGraphic { get; } - ModerationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModerationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ModerationResult(ClientResult result); + public static implicit operator BinaryContent(ModerationResult moderationResult); } public class ModerationResultCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { public string Id { get; } public string Model { get; } - ModerationResultCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModerationResultCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ModerationResultCollection(ClientResult result); + public static implicit operator BinaryContent(ModerationResultCollection moderationResultCollection); } public static class OpenAIModerationsModelFactory { public static ModerationCategory ModerationCategory(bool flagged = false, float score = 0); @@ -2228,8 +1929,6 @@ public static class OpenAIModerationsModelFactory { } namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationAudioFormat : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationAudioFormat(string value); public static ConversationAudioFormat G711Alaw { get; } public static ConversationAudioFormat G711Ulaw { get; } @@ -2256,16 +1955,11 @@ public abstract class ConversationContentPart : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public readonly partial struct ConversationContentPartKind : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationContentPartKind(string value); public static ConversationContentPartKind InputAudio { get; } public static ConversationContentPartKind InputText { get; } @@ -2286,11 +1980,12 @@ public class ConversationErrorUpdate : ConversationUpdate, IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationErrorUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationErrorUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationErrorUpdate conversationErrorUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationFunctionTool : ConversationTool, IJsonModel, IPersistableModel { public ConversationFunctionTool(); @@ -2298,55 +1993,57 @@ public class ConversationFunctionTool : ConversationTool, IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationFunctionTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationTool JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationFunctionTool(ClientResult result); + public static implicit operator BinaryContent(ConversationFunctionTool conversationFunctionTool); + protected override ConversationTool PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputAudioClearedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { - ConversationInputAudioClearedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputAudioClearedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputAudioClearedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputAudioClearedUpdate conversationInputAudioClearedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputAudioCommittedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string ItemId { get; } public string PreviousItemId { get; } - ConversationInputAudioCommittedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputAudioCommittedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputAudioCommittedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputAudioCommittedUpdate conversationInputAudioCommittedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputSpeechFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public TimeSpan AudioEndTime { get; } public string ItemId { get; } - ConversationInputSpeechFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputSpeechFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputSpeechFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputSpeechFinishedUpdate conversationInputSpeechFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputSpeechStartedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public TimeSpan AudioStartTime { get; } public string ItemId { get; } - ConversationInputSpeechStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputSpeechStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputSpeechStartedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputSpeechStartedUpdate conversationInputSpeechStartedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputTokenUsageDetails : IJsonModel, IPersistableModel { public int AudioTokens { get; } public int CachedTokens { get; } public int TextTokens { get; } - ConversationInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationInputTokenUsageDetails(ClientResult result); + public static implicit operator BinaryContent(ConversationInputTokenUsageDetails conversationInputTokenUsageDetails); } public class ConversationInputTranscriptionFailedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public int ContentIndex { get; } @@ -2354,29 +2051,28 @@ public class ConversationInputTranscriptionFailedUpdate : ConversationUpdate, IJ public string ErrorMessage { get; } public string ErrorParameterName { get; } public string ItemId { get; } - ConversationInputTranscriptionFailedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputTranscriptionFailedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputTranscriptionFailedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputTranscriptionFailedUpdate conversationInputTranscriptionFailedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputTranscriptionFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public int ContentIndex { get; } public string ItemId { get; } public string Transcript { get; } - ConversationInputTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputTranscriptionFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationInputTranscriptionFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationInputTranscriptionFinishedUpdate conversationInputTranscriptionFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationInputTranscriptionOptions : IJsonModel, IPersistableModel { public ConversationTranscriptionModel? Model { get; set; } - ConversationInputTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationInputTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationInputTranscriptionOptions(ClientResult result); + public static implicit operator BinaryContent(ConversationInputTranscriptionOptions conversationInputTranscriptionOptions); } public abstract class ConversationItem : IJsonModel, IPersistableModel { public string FunctionArguments { get; } @@ -2390,11 +2086,8 @@ public abstract class ConversationItem : IJsonModel, IPersista public static ConversationItem CreateFunctionCallOutput(string callId, string output); public static ConversationItem CreateSystemMessage(IEnumerable contentItems); public static ConversationItem CreateUserMessage(IEnumerable contentItems); - ConversationItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationItem(ClientResult result); + public static implicit operator BinaryContent(ConversationItem conversationItem); } public class ConversationItemCreatedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string FunctionCallArguments { get; } @@ -2405,23 +2098,23 @@ public class ConversationItemCreatedUpdate : ConversationUpdate, IJsonModel MessageContentParts { get; } public ConversationMessageRole? MessageRole { get; } public string PreviousItemId { get; } - ConversationItemCreatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemCreatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemCreatedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemCreatedUpdate conversationItemCreatedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemDeletedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string ItemId { get; } - ConversationItemDeletedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemDeletedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemDeletedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemDeletedUpdate conversationItemDeletedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public readonly partial struct ConversationItemStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationItemStatus(string value); public static ConversationItemStatus Completed { get; } public static ConversationItemStatus Incomplete { get; } @@ -2441,11 +2134,12 @@ public class ConversationItemStreamingAudioFinishedUpdate : ConversationUpdate, public string ItemId { get; } public int OutputIndex { get; } public string ResponseId { get; } - ConversationItemStreamingAudioFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingAudioFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemStreamingAudioFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemStreamingAudioFinishedUpdate conversationItemStreamingAudioFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemStreamingAudioTranscriptionFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public int ContentIndex { get; } @@ -2453,11 +2147,12 @@ public class ConversationItemStreamingAudioTranscriptionFinishedUpdate : Convers public int OutputIndex { get; } public string ResponseId { get; } public string Transcript { get; } - ConversationItemStreamingAudioTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingAudioTranscriptionFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemStreamingAudioTranscriptionFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemStreamingAudioTranscriptionFinishedUpdate conversationItemStreamingAudioTranscriptionFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemStreamingFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string FunctionCallArguments { get; } @@ -2469,11 +2164,12 @@ public class ConversationItemStreamingFinishedUpdate : ConversationUpdate, IJson public ConversationMessageRole? MessageRole { get; } public int OutputIndex { get; } public string ResponseId { get; } - ConversationItemStreamingFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemStreamingFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemStreamingFinishedUpdate conversationItemStreamingFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemStreamingPartDeltaUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public BinaryData AudioBytes { get; } @@ -2485,11 +2181,6 @@ public class ConversationItemStreamingPartDeltaUpdate : ConversationUpdate, IJso public int ItemIndex { get; } public string ResponseId { get; } public string Text { get; } - ConversationItemStreamingPartDeltaUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingPartDeltaUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class ConversationItemStreamingPartFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string AudioTranscript { get; } @@ -2500,11 +2191,6 @@ public class ConversationItemStreamingPartFinishedUpdate : ConversationUpdate, I public int ItemIndex { get; } public string ResponseId { get; } public string Text { get; } - ConversationItemStreamingPartFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingPartFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class ConversationItemStreamingStartedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public string FunctionCallArguments { get; } @@ -2516,11 +2202,12 @@ public class ConversationItemStreamingStartedUpdate : ConversationUpdate, IJsonM public IReadOnlyList MessageContentParts { get; } public ConversationMessageRole? MessageRole { get; } public string ResponseId { get; } - ConversationItemStreamingStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemStreamingStartedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemStreamingStartedUpdate conversationItemStreamingStartedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemStreamingTextFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public int ContentIndex { get; } @@ -2528,21 +2215,23 @@ public class ConversationItemStreamingTextFinishedUpdate : ConversationUpdate, I public int OutputIndex { get; } public string ResponseId { get; } public string Text { get; } - ConversationItemStreamingTextFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemStreamingTextFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemStreamingTextFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemStreamingTextFinishedUpdate conversationItemStreamingTextFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationItemTruncatedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public int AudioEndMs { get; } public int ContentIndex { get; } public string ItemId { get; } - ConversationItemTruncatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationItemTruncatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationItemTruncatedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationItemTruncatedUpdate conversationItemTruncatedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationMaxTokensChoice : IJsonModel, IPersistableModel { public ConversationMaxTokensChoice(int numberValue); @@ -2551,15 +2240,8 @@ public class ConversationMaxTokensChoice : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationMaxTokensChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public readonly partial struct ConversationMessageRole : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationMessageRole(string value); public static ConversationMessageRole Assistant { get; } public static ConversationMessageRole System { get; } @@ -2577,32 +2259,27 @@ public class ConversationMaxTokensChoice : IJsonModel, IPersistableModel { public int AudioTokens { get; } public int TextTokens { get; } - ConversationOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationOutputTokenUsageDetails(ClientResult result); + public static implicit operator BinaryContent(ConversationOutputTokenUsageDetails conversationOutputTokenUsageDetails); } public class ConversationRateLimitDetailsItem : IJsonModel, IPersistableModel { public int MaximumCount { get; } public string Name { get; } public int RemainingCount { get; } public TimeSpan TimeUntilReset { get; } - ConversationRateLimitDetailsItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationRateLimitDetailsItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationRateLimitDetailsItem(ClientResult result); + public static implicit operator BinaryContent(ConversationRateLimitDetailsItem conversationRateLimitDetailsItem); } public class ConversationRateLimitsUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public IReadOnlyList AllDetails { get; } public ConversationRateLimitDetailsItem RequestDetails { get; } public ConversationRateLimitDetailsItem TokenDetails { get; } - ConversationRateLimitsUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationRateLimitsUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationRateLimitsUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationRateLimitsUpdate conversationRateLimitsUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationResponseFinishedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public IReadOnlyList CreatedItems { get; } @@ -2610,11 +2287,12 @@ public class ConversationResponseFinishedUpdate : ConversationUpdate, IJsonModel public ConversationStatus? Status { get; } public ConversationStatusDetails StatusDetails { get; } public ConversationTokenUsage Usage { get; } - ConversationResponseFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationResponseFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationResponseFinishedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationResponseFinishedUpdate conversationResponseFinishedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationResponseStartedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public IReadOnlyList CreatedItems { get; } @@ -2622,11 +2300,12 @@ public class ConversationResponseStartedUpdate : ConversationUpdate, IJsonModel< public ConversationStatus Status { get; } public ConversationStatusDetails StatusDetails { get; } public ConversationTokenUsage Usage { get; } - ConversationResponseStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationResponseStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationResponseStartedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationResponseStartedUpdate conversationResponseStartedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationSessionConfiguredUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public ConversationContentModalities ContentModalities { get; } @@ -2642,11 +2321,12 @@ public class ConversationSessionConfiguredUpdate : ConversationUpdate, IJsonMode public IReadOnlyList Tools { get; } public ConversationTurnDetectionOptions TurnDetectionOptions { get; } public ConversationVoice Voice { get; } - ConversationSessionConfiguredUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationSessionConfiguredUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationSessionConfiguredUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationSessionConfiguredUpdate conversationSessionConfiguredUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class ConversationSessionOptions : IJsonModel, IPersistableModel { public ConversationContentModalities ContentModalities { get; set; } @@ -2660,11 +2340,8 @@ public class ConversationSessionOptions : IJsonModel public IList Tools { get; } public ConversationTurnDetectionOptions TurnDetectionOptions { get; set; } public ConversationVoice? Voice { get; set; } - ConversationSessionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationSessionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationSessionOptions(ClientResult result); + public static implicit operator BinaryContent(ConversationSessionOptions conversationSessionOptions); } public class ConversationSessionStartedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public ConversationContentModalities ContentModalities { get; } @@ -2680,15 +2357,14 @@ public class ConversationSessionStartedUpdate : ConversationUpdate, IJsonModel Tools { get; } public ConversationTurnDetectionOptions TurnDetectionOptions { get; } public ConversationVoice Voice { get; } - ConversationSessionStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationSessionStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator ConversationSessionStartedUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationSessionStartedUpdate conversationSessionStartedUpdate); + protected override ConversationUpdate PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public readonly partial struct ConversationStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationStatus(string value); public static ConversationStatus Cancelled { get; } public static ConversationStatus Completed { get; } @@ -2707,11 +2383,8 @@ public class ConversationSessionStartedUpdate : ConversationUpdate, IJsonModel, IPersistableModel { public ConversationStatus StatusKind { get; } - ConversationStatusDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationStatusDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationStatusDetails(ClientResult result); + public static implicit operator BinaryContent(ConversationStatusDetails conversationStatusDetails); } public class ConversationTokenUsage : IJsonModel, IPersistableModel { public ConversationInputTokenUsageDetails InputTokenDetails { get; } @@ -2719,20 +2392,14 @@ public class ConversationTokenUsage : IJsonModel, IPersi public ConversationOutputTokenUsageDetails OutputTokenDetails { get; } public int OutputTokens { get; } public int TotalTokens { get; } - ConversationTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationTokenUsage(ClientResult result); + public static implicit operator BinaryContent(ConversationTokenUsage conversationTokenUsage); } public abstract class ConversationTool : IJsonModel, IPersistableModel { public ConversationToolKind Kind { get; } public static ConversationTool CreateFunctionTool(string name, string description = null, BinaryData parameters = null); - ConversationTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationTool(ClientResult result); + public static implicit operator BinaryContent(ConversationTool conversationTool); } public class ConversationToolChoice : IJsonModel, IPersistableModel { public string FunctionName { get; } @@ -2741,11 +2408,6 @@ public class ConversationToolChoice : IJsonModel, IPersi public static ConversationToolChoice CreateFunctionToolChoice(string functionName); public static ConversationToolChoice CreateNoneToolChoice(); public static ConversationToolChoice CreateRequiredToolChoice(); - ConversationToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public enum ConversationToolChoiceKind { Unknown = 0, @@ -2755,8 +2417,6 @@ public enum ConversationToolChoiceKind { Function = 4 } public readonly partial struct ConversationToolKind : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationToolKind(string value); public static ConversationToolKind Function { get; } public readonly bool Equals(ConversationToolKind other); @@ -2770,8 +2430,6 @@ public enum ConversationToolChoiceKind { public override readonly string ToString(); } public readonly partial struct ConversationTranscriptionModel : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationTranscriptionModel(string value); public static ConversationTranscriptionModel Whisper1 { get; } public readonly bool Equals(ConversationTranscriptionModel other); @@ -2792,22 +2450,15 @@ public abstract class ConversationTurnDetectionOptions : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationTurnDetectionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationTurnDetectionOptions(ClientResult result); + public static implicit operator BinaryContent(ConversationTurnDetectionOptions conversationTurnDetectionOptions); } public abstract class ConversationUpdate : IJsonModel, IPersistableModel { - protected ConversationUpdate(string eventId); public string EventId { get; } public ConversationUpdateKind Kind { get; protected internal set; } public BinaryData GetRawContent(); - ConversationUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ConversationUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator ConversationUpdate(ClientResult result); + public static implicit operator BinaryContent(ConversationUpdate conversationUpdate); } public enum ConversationUpdateKind { Unknown = 0, @@ -2841,8 +2492,6 @@ public enum ConversationUpdateKind { Error = 28 } public readonly partial struct ConversationVoice : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public ConversationVoice(string value); public static ConversationVoice Alloy { get; } public static ConversationVoice Echo { get; } @@ -2862,7 +2511,7 @@ public class RealtimeConversationClient { protected internal RealtimeConversationClient(ClientPipeline pipeline, OpenAIClientOptions options); public RealtimeConversationClient(string model, ApiKeyCredential credential, OpenAIClientOptions options); public RealtimeConversationClient(string model, ApiKeyCredential credential); - public virtual ClientPipeline Pipeline { get; } + public ClientPipeline Pipeline { get; } public event EventHandler OnReceivingCommand { add; remove; } public event EventHandler OnSendingCommand { add; remove; } public RealtimeConversationSession StartConversationSession(CancellationToken cancellationToken = default); @@ -2976,30 +2625,25 @@ public abstract class FileChunkingStrategy : IJsonModel, I public static FileChunkingStrategy Auto { get; } public static FileChunkingStrategy Unknown { get; } public static FileChunkingStrategy CreateStaticStrategy(int maxTokensPerChunk, int overlappingTokenCount); - FileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator FileChunkingStrategy(ClientResult result); + public static implicit operator BinaryContent(FileChunkingStrategy fileChunkingStrategy); } public class FileFromStoreRemovalResult : IJsonModel, IPersistableModel { public string FileId { get; } public bool Removed { get; } - FileFromStoreRemovalResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - FileFromStoreRemovalResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator FileFromStoreRemovalResult(ClientResult result); + public static implicit operator BinaryContent(FileFromStoreRemovalResult fileFromStoreRemovalResult); } public class StaticFileChunkingStrategy : FileChunkingStrategy, IJsonModel, IPersistableModel { public StaticFileChunkingStrategy(int maxTokensPerChunk, int overlappingTokenCount); public int MaxTokensPerChunk { get; } public int OverlappingTokenCount { get; } - StaticFileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - StaticFileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + protected override FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options); + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options); + public new static explicit operator StaticFileChunkingStrategy(ClientResult result); + public static implicit operator BinaryContent(StaticFileChunkingStrategy staticFileChunkingStrategy); + protected override FileChunkingStrategy PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options); } public class VectorStore : IJsonModel, IPersistableModel { public DateTimeOffset CreatedAt { get; } @@ -3012,11 +2656,8 @@ public class VectorStore : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStore(ClientResult result); + public static implicit operator BinaryContent(VectorStore vectorStore); } public class VectorStoreBatchFileJob : IJsonModel, IPersistableModel { public string BatchId { get; } @@ -3024,15 +2665,10 @@ public class VectorStoreBatchFileJob : IJsonModel, IPer public VectorStoreFileCounts FileCounts { get; } public VectorStoreBatchFileJobStatus Status { get; } public string VectorStoreId { get; } - VectorStoreBatchFileJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreBatchFileJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreBatchFileJob(ClientResult result); + public static implicit operator BinaryContent(VectorStoreBatchFileJob vectorStoreBatchFileJob); } public readonly partial struct VectorStoreBatchFileJobStatus : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public VectorStoreBatchFileJobStatus(string value); public static VectorStoreBatchFileJobStatus Cancelled { get; } public static VectorStoreBatchFileJobStatus Completed { get; } @@ -3140,8 +2776,6 @@ public class VectorStoreCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct VectorStoreCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public VectorStoreCollectionOrder(string value); public static VectorStoreCollectionOrder Ascending { get; } public static VectorStoreCollectionOrder Descending { get; } @@ -3161,20 +2795,14 @@ public class VectorStoreCreationOptions : IJsonModel public IList FileIds { get; } public IDictionary Metadata { get; set; } public string Name { get; set; } - VectorStoreCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreCreationOptions(ClientResult result); + public static implicit operator BinaryContent(VectorStoreCreationOptions vectorStoreCreationOptions); } public class VectorStoreDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } public string VectorStoreId { get; } - VectorStoreDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreDeletionResult(ClientResult result); + public static implicit operator BinaryContent(VectorStoreDeletionResult vectorStoreDeletionResult); } public enum VectorStoreExpirationAnchor { Unknown = 0, @@ -3185,11 +2813,8 @@ public class VectorStoreExpirationPolicy : IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreExpirationPolicy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreExpirationPolicy(ClientResult result); + public static implicit operator BinaryContent(VectorStoreExpirationPolicy vectorStoreExpirationPolicy); } public class VectorStoreFileAssociation : IJsonModel, IPersistableModel { public FileChunkingStrategy ChunkingStrategy { get; } @@ -3199,11 +2824,8 @@ public class VectorStoreFileAssociation : IJsonModel public int Size { get; } public VectorStoreFileAssociationStatus Status { get; } public string VectorStoreId { get; } - VectorStoreFileAssociation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreFileAssociation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreFileAssociation(ClientResult result); + public static implicit operator BinaryContent(VectorStoreFileAssociation vectorStoreFileAssociation); } public class VectorStoreFileAssociationCollectionOptions { public string AfterId { get; set; } @@ -3213,8 +2835,6 @@ public class VectorStoreFileAssociationCollectionOptions { public int? PageSizeLimit { get; set; } } public readonly partial struct VectorStoreFileAssociationCollectionOrder : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public VectorStoreFileAssociationCollectionOrder(string value); public static VectorStoreFileAssociationCollectionOrder Ascending { get; } public static VectorStoreFileAssociationCollectionOrder Descending { get; } @@ -3231,15 +2851,10 @@ public class VectorStoreFileAssociationCollectionOptions { public class VectorStoreFileAssociationError : IJsonModel, IPersistableModel { public VectorStoreFileAssociationErrorCode Code { get; } public string Message { get; } - VectorStoreFileAssociationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreFileAssociationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreFileAssociationError(ClientResult result); + public static implicit operator BinaryContent(VectorStoreFileAssociationError vectorStoreFileAssociationError); } public readonly partial struct VectorStoreFileAssociationErrorCode : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public VectorStoreFileAssociationErrorCode(string value); public static VectorStoreFileAssociationErrorCode InvalidFile { get; } public static VectorStoreFileAssociationErrorCode ServerError { get; } @@ -3267,15 +2882,10 @@ public class VectorStoreFileCounts : IJsonModel, IPersist public int Failed { get; } public int InProgress { get; } public int Total { get; } - VectorStoreFileCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreFileCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreFileCounts(ClientResult result); + public static implicit operator BinaryContent(VectorStoreFileCounts vectorStoreFileCounts); } public readonly partial struct VectorStoreFileStatusFilter : IEquatable { - private readonly object _dummy; - private readonly int _dummyPrimitive; public VectorStoreFileStatusFilter(string value); public static VectorStoreFileStatusFilter Cancelled { get; } public static VectorStoreFileStatusFilter Completed { get; } @@ -3295,11 +2905,8 @@ public class VectorStoreModificationOptions : IJsonModel Metadata { get; set; } public string Name { get; set; } - VectorStoreModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - VectorStoreModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public static explicit operator VectorStoreModificationOptions(ClientResult result); + public static implicit operator BinaryContent(VectorStoreModificationOptions vectorStoreModificationOptions); } public enum VectorStoreStatus { Unknown = 0, diff --git a/nuget.config b/nuget.config index 2805dff37..54e660f9c 100644 --- a/nuget.config +++ b/nuget.config @@ -1,8 +1,8 @@ - + - + \ No newline at end of file diff --git a/src/Custom/Assistants/AssistantClient.Protocol.cs b/src/Custom/Assistants/AssistantClient.Protocol.cs index 73e154142..e964ca737 100644 --- a/src/Custom/Assistants/AssistantClient.Protocol.cs +++ b/src/Custom/Assistants/AssistantClient.Protocol.cs @@ -6,6 +6,8 @@ namespace OpenAI.Assistants; +[CodeGenSuppress("ListAssistantsAsync", typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListAssistants", typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] public partial class AssistantClient { /// @@ -22,7 +24,7 @@ public virtual async Task CreateAssistantAsync(BinaryContent conte Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateAssistantRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -39,7 +41,7 @@ public virtual ClientResult CreateAssistant(BinaryContent content, RequestOption Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateAssistantRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -69,7 +71,7 @@ public virtual ClientResult CreateAssistant(BinaryContent content, RequestOption [EditorBrowsable(EditorBrowsableState.Never)] public virtual AsyncCollectionResult GetAssistantsAsync(int? limit, string order, string after, string before, RequestOptions options) { - return new AsyncAssistantCollectionResult(this, _pipeline, options, limit, order, after, before); + return new AsyncAssistantCollectionResult(this, Pipeline, options, limit, order, after, before); } /// @@ -99,7 +101,7 @@ public virtual AsyncCollectionResult GetAssistantsAsync(int? limit, string order [EditorBrowsable(EditorBrowsableState.Never)] public virtual CollectionResult GetAssistants(int? limit, string order, string after, string before, RequestOptions options) { - return new AssistantCollectionResult(this, _pipeline, options, limit, order, after, before); + return new AssistantCollectionResult(this, Pipeline, options, limit, order, after, before); } /// @@ -117,7 +119,7 @@ public virtual async Task GetAssistantAsync(string assistantId, Re Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); using PipelineMessage message = CreateGetAssistantRequest(assistantId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -135,7 +137,7 @@ public virtual ClientResult GetAssistant(string assistantId, RequestOptions opti Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); using PipelineMessage message = CreateGetAssistantRequest(assistantId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -155,7 +157,7 @@ public virtual async Task ModifyAssistantAsync(string assistantId, Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyAssistantRequest(assistantId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -175,7 +177,7 @@ public virtual ClientResult ModifyAssistant(string assistantId, BinaryContent co Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyAssistantRequest(assistantId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -193,7 +195,7 @@ public virtual async Task DeleteAssistantAsync(string assistantId, Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); using PipelineMessage message = CreateDeleteAssistantRequest(assistantId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -211,7 +213,7 @@ public virtual ClientResult DeleteAssistant(string assistantId, RequestOptions o Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); using PipelineMessage message = CreateDeleteAssistantRequest(assistantId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// diff --git a/src/Custom/Assistants/AssistantClient.cs b/src/Custom/Assistants/AssistantClient.cs index 69fc57240..408bcb7e0 100644 --- a/src/Custom/Assistants/AssistantClient.cs +++ b/src/Custom/Assistants/AssistantClient.cs @@ -14,30 +14,24 @@ namespace OpenAI.Assistants; [Experimental("OPENAI001")] [CodeGenClient("Assistants")] [CodeGenSuppress("AssistantClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateAssistantAsync", typeof(AssistantCreationOptions))] -[CodeGenSuppress("CreateAssistant", typeof(AssistantCreationOptions))] +[CodeGenSuppress("CreateAssistantAsync", typeof(AssistantCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateAssistant", typeof(AssistantCreationOptions), typeof(CancellationToken))] [CodeGenSuppress("GetAssistantAsync", typeof(string))] [CodeGenSuppress("GetAssistant", typeof(string))] [CodeGenSuppress("ModifyAssistantAsync", typeof(string), typeof(AssistantModificationOptions))] [CodeGenSuppress("ModifyAssistant", typeof(string), typeof(AssistantModificationOptions))] [CodeGenSuppress("DeleteAssistantAsync", typeof(string))] [CodeGenSuppress("DeleteAssistant", typeof(string))] -[CodeGenSuppress("GetAssistantsAsync", typeof(int?), typeof(AssistantCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetAssistants", typeof(int?), typeof(AssistantCollectionOrder?), typeof(string), typeof(string))] +[CodeGenSuppress("ListAssistantsAsync", typeof(int?), typeof(AssistantCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListAssistants", typeof(int?), typeof(AssistantCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] public partial class AssistantClient { private readonly InternalAssistantMessageClient _messageSubClient; private readonly InternalAssistantRunClient _runSubClient; private readonly InternalAssistantThreadClient _threadSubClient; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public AssistantClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -47,7 +41,7 @@ public partial class AssistantClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public AssistantClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -57,7 +51,7 @@ public partial class AssistantClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -66,18 +60,18 @@ public AssistantClient(ApiKeyCredential credential, OpenAIClientOptions options) Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); - _messageSubClient = new(_pipeline, options); - _runSubClient = new(_pipeline, options); - _threadSubClient = new(_pipeline, options); + _messageSubClient = new(Pipeline, options); + _runSubClient = new(Pipeline, options); + _threadSubClient = new(Pipeline, options); } // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -86,11 +80,11 @@ protected internal AssistantClient(ClientPipeline pipeline, OpenAIClientOptions Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); - _messageSubClient = new(_pipeline, options); - _runSubClient = new(_pipeline, options); - _threadSubClient = new(_pipeline, options); + _messageSubClient = new(Pipeline, options); + _runSubClient = new(Pipeline, options); + _threadSubClient = new(Pipeline, options); } /// Creates a new assistant. @@ -104,8 +98,8 @@ public virtual async Task> CreateAssistantAsync(string m options ??= new(); options.Model = model; - ClientResult protocolResult = await CreateAssistantAsync(options?.ToBinaryContent(), cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + ClientResult protocolResult = await CreateAssistantAsync(options, cancellationToken.ToRequestOptions()).ConfigureAwait(false); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// Creates a new assistant. @@ -119,8 +113,8 @@ public virtual ClientResult CreateAssistant(string model, AssistantCr options ??= new(); options.Model = model; - ClientResult protocolResult = CreateAssistant(options?.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + ClientResult protocolResult = CreateAssistant(options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// @@ -220,7 +214,7 @@ public virtual async Task> GetAssistantAsync(string assi Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); ClientResult protocolResult = await GetAssistantAsync(assistantId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// @@ -234,7 +228,7 @@ public virtual ClientResult GetAssistant(string assistantId, Cancella Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); ClientResult protocolResult = GetAssistant(assistantId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// @@ -249,10 +243,10 @@ public virtual async Task> ModifyAssistantAsync(string a Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(options, nameof(options)); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult protocolResult = await ModifyAssistantAsync(assistantId, content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// @@ -267,13 +261,13 @@ public virtual ClientResult ModifyAssistant(string assistantId, Assis Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(options, nameof(options)); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult protocolResult = ModifyAssistant(assistantId, content, null); - return CreateResultFromProtocol(protocolResult, Assistant.FromResponse); + return ClientResult.FromValue((Assistant)protocolResult, protocolResult.GetRawResponse()); } /// - /// Deletes an existing . + /// Deletes an existing . /// /// The ID of the assistant to delete. /// A token that can be used to cancel this method call. @@ -283,12 +277,11 @@ public virtual async Task> DeleteAssistant Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); ClientResult protocolResult = await DeleteAssistantAsync(assistantId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, response - => AssistantDeletionResult.FromResponse(response)); + return ClientResult.FromValue((AssistantDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// - /// Deletes an existing . + /// Deletes an existing . /// /// The ID of the assistant to delete. /// A token that can be used to cancel this method call. @@ -298,8 +291,7 @@ public virtual ClientResult DeleteAssistant(string assi Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); ClientResult protocolResult = DeleteAssistant(assistantId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, response - => AssistantDeletionResult.FromResponse(response)); + return ClientResult.FromValue((AssistantDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// @@ -310,8 +302,8 @@ public virtual ClientResult DeleteAssistant(string assi /// A new thread. public virtual async Task> CreateThreadAsync(ThreadCreationOptions options = null, CancellationToken cancellationToken = default) { - ClientResult protocolResult = await CreateThreadAsync(options?.ToBinaryContent(), cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + ClientResult protocolResult = await CreateThreadAsync(options, cancellationToken.ToRequestOptions()).ConfigureAwait(false); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -322,8 +314,8 @@ public virtual async Task> CreateThreadAsync(Threa /// A new thread. public virtual ClientResult CreateThread(ThreadCreationOptions options = null, CancellationToken cancellationToken = default) { - ClientResult protocolResult = CreateThread(options?.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + ClientResult protocolResult = CreateThread(options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -337,7 +329,7 @@ public virtual async Task> GetThreadAsync(string t Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); ClientResult protocolResult = await GetThreadAsync(threadId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -351,7 +343,7 @@ public virtual ClientResult GetThread(string threadId, Cancella Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); ClientResult protocolResult = GetThread(threadId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -366,8 +358,8 @@ public virtual async Task> ModifyThreadAsync(strin Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(options, nameof(options)); - ClientResult protocolResult = await ModifyThreadAsync(threadId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + ClientResult protocolResult = await ModifyThreadAsync(threadId, options, cancellationToken.ToRequestOptions()).ConfigureAwait(false); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -382,8 +374,8 @@ public virtual ClientResult ModifyThread(string threadId, Threa Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(options, nameof(options)); - ClientResult protocolResult = ModifyThread(threadId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, AssistantThread.FromResponse); + ClientResult protocolResult = ModifyThread(threadId, options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((AssistantThread)protocolResult, protocolResult.GetRawResponse()); } /// @@ -397,8 +389,7 @@ public virtual async Task> DeleteThreadAsync( Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); ClientResult protocolResult = await DeleteThreadAsync(threadId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, response - => ThreadDeletionResult.FromResponse(response)); + return ClientResult.FromValue((ThreadDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// @@ -412,8 +403,7 @@ public virtual ClientResult DeleteThread(string threadId, Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); ClientResult protocolResult = DeleteThread(threadId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, response - => ThreadDeletionResult.FromResponse(response)); + return ClientResult.FromValue((ThreadDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// @@ -441,9 +431,9 @@ public virtual async Task> CreateMessageAsync( options.Content.Add(contentItem); } - ClientResult protocolResult = await CreateMessageAsync(threadId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()) + ClientResult protocolResult = await CreateMessageAsync(threadId, options, cancellationToken.ToRequestOptions()) .ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -471,8 +461,8 @@ public virtual ClientResult CreateMessage( options.Content.Add(contentItem); } - ClientResult protocolResult = CreateMessage(threadId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + ClientResult protocolResult = CreateMessage(threadId, options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -583,7 +573,7 @@ public virtual async Task> GetMessageAsync(string th Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); ClientResult protocolResult = await GetMessageAsync(threadId, messageId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -599,7 +589,7 @@ public virtual ClientResult GetMessage(string threadId, string me Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); ClientResult protocolResult = GetMessage(threadId, messageId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -616,9 +606,9 @@ public virtual async Task> ModifyMessageAsync(string Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNull(options, nameof(options)); - ClientResult protocolResult = await ModifyMessageAsync(threadId, messageId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()) + ClientResult protocolResult = await ModifyMessageAsync(threadId, messageId, options, cancellationToken.ToRequestOptions()) .ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -635,8 +625,8 @@ public virtual ClientResult ModifyMessage(string threadId, string Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNull(options, nameof(options)); - ClientResult protocolResult = ModifyMessage(threadId, messageId, options?.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadMessage.FromResponse); + ClientResult protocolResult = ModifyMessage(threadId, messageId, options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((ThreadMessage)protocolResult, protocolResult.GetRawResponse()); } /// @@ -652,8 +642,7 @@ public virtual async Task> DeleteMessageAsyn Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); ClientResult protocolResult = await DeleteMessageAsync(threadId, messageId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, response => - MessageDeletionResult.FromResponse(response)); + return ClientResult.FromValue((MessageDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// @@ -669,8 +658,7 @@ public virtual ClientResult DeleteMessage(string threadId Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); ClientResult protocolResult = DeleteMessage(threadId, messageId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, response => - MessageDeletionResult.FromResponse(response)); + return ClientResult.FromValue((MessageDeletionResult)protocolResult, protocolResult.GetRawResponse()); } /// @@ -690,9 +678,9 @@ public virtual async Task> CreateRunAsync(string threadI options.AssistantId = assistantId; options.Stream = null; - ClientResult protocolResult = await CreateRunAsync(threadId, options.ToBinaryContent(), cancellationToken.ToRequestOptions()) + ClientResult protocolResult = await CreateRunAsync(threadId, options, cancellationToken.ToRequestOptions()) .ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -712,8 +700,8 @@ public virtual ClientResult CreateRun(string threadId, string assista options.AssistantId = assistantId; options.Stream = null; - ClientResult protocolResult = CreateRun(threadId, options.ToBinaryContent(), cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + ClientResult protocolResult = CreateRun(threadId, options, cancellationToken.ToRequestOptions()); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -738,7 +726,7 @@ public virtual AsyncCollectionResult CreateRunStreamingAsync( options.Stream = true; async Task sendRequestAsync() => - await CreateRunAsync(threadId, options.ToBinaryContent(), cancellationToken.ToRequestOptions(streaming: true)) + await CreateRunAsync(threadId, options, cancellationToken.ToRequestOptions(streaming: true)) .ConfigureAwait(false); return new AsyncStreamingUpdateCollection(sendRequestAsync, cancellationToken); @@ -765,7 +753,7 @@ public virtual CollectionResult CreateRunStreaming( options.AssistantId = assistantId; options.Stream = true; - ClientResult sendRequest() => CreateRun(threadId, options.ToBinaryContent(), cancellationToken.ToRequestOptions(streaming: true)); + ClientResult sendRequest() => CreateRun(threadId, options, cancellationToken.ToRequestOptions(streaming: true)); return new StreamingUpdateCollection(sendRequest, cancellationToken); } @@ -787,7 +775,7 @@ public virtual async Task> CreateThreadAndRunAsync( runOptions.Stream = null; BinaryContent protocolContent = CreateThreadAndRunProtocolContent(assistantId, threadOptions, runOptions); ClientResult protocolResult = await CreateThreadAndRunAsync(protocolContent, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -808,7 +796,7 @@ public virtual ClientResult CreateThreadAndRun( runOptions.Stream = null; BinaryContent protocolContent = CreateThreadAndRunProtocolContent(assistantId, threadOptions, runOptions); ClientResult protocolResult = CreateThreadAndRun(protocolContent, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -967,7 +955,7 @@ public virtual async Task> GetRunAsync(string threadId, Argument.AssertNotNullOrEmpty(runId, nameof(runId)); ClientResult protocolResult = await GetRunAsync(threadId, runId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -983,7 +971,7 @@ public virtual ClientResult GetRun(string threadId, string runId, Can Argument.AssertNotNullOrEmpty(runId, nameof(runId)); ClientResult protocolResult = GetRun(threadId, runId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1005,10 +993,10 @@ public virtual async Task> SubmitToolOutputsToRunAsync( Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs).ToBinaryContent(); + BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs); ClientResult protocolResult = await SubmitToolOutputsToRunAsync(threadId, runId, content, cancellationToken.ToRequestOptions()) .ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1030,9 +1018,9 @@ public virtual ClientResult SubmitToolOutputsToRun( Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs).ToBinaryContent(); + BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs); ClientResult protocolResult = SubmitToolOutputsToRun(threadId, runId, content, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1053,8 +1041,7 @@ public virtual AsyncCollectionResult SubmitToolOutputsToRunStre Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs.ToList(), stream: true, null) - .ToBinaryContent(); + BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs.ToList(), stream: true, null); async Task sendRequestAsync() => await SubmitToolOutputsToRunAsync(threadId, runId, content, cancellationToken.ToRequestOptions(streaming: true)) @@ -1081,8 +1068,7 @@ public virtual CollectionResult SubmitToolOutputsToRunStreaming Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs.ToList(), stream: true, null) - .ToBinaryContent(); + BinaryContent content = new InternalSubmitToolOutputsRunRequest(toolOutputs.ToList(), stream: true, null); ClientResult sendRequest() => SubmitToolOutputsToRun(threadId, runId, content, cancellationToken.ToRequestOptions(streaming: true)); return new StreamingUpdateCollection(sendRequest, cancellationToken); @@ -1101,7 +1087,7 @@ public virtual async Task> CancelRunAsync(string threadI Argument.AssertNotNullOrEmpty(runId, nameof(runId)); ClientResult protocolResult = await CancelRunAsync(threadId, runId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1117,7 +1103,7 @@ public virtual ClientResult CancelRun(string threadId, string runId, Argument.AssertNotNullOrEmpty(runId, nameof(runId)); ClientResult protocolResult = CancelRun(threadId, runId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, ThreadRun.FromResponse); + return ClientResult.FromValue((ThreadRun)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1225,7 +1211,7 @@ public virtual CollectionResult GetRunSteps( public virtual async Task> GetRunStepAsync(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) { ClientResult protocolResult = await GetRunStepAsync(threadId, runId, stepId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return CreateResultFromProtocol(protocolResult, RunStep.FromResponse); + return ClientResult.FromValue((RunStep)protocolResult, protocolResult.GetRawResponse()); } /// @@ -1239,7 +1225,7 @@ public virtual async Task> GetRunStepAsync(string threadId public virtual ClientResult GetRunStep(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) { ClientResult protocolResult = GetRunStep(threadId, runId, stepId, cancellationToken.ToRequestOptions()); - return CreateResultFromProtocol(protocolResult, RunStep.FromResponse); + return ClientResult.FromValue((RunStep)protocolResult, protocolResult.GetRawResponse()); } private static BinaryContent CreateThreadAndRunProtocolContent( @@ -1251,23 +1237,23 @@ private static BinaryContent CreateThreadAndRunProtocolContent( InternalCreateThreadAndRunRequest internalRequest = new( assistantId, threadOptions, - runOptions.ModelOverride, runOptions.InstructionsOverride, runOptions.ToolsOverride, - // TODO: reconcile exposure of the the two different tool_resources, if needed - threadOptions?.ToolResources, runOptions.Metadata, runOptions.Temperature, + // TODO: reconcile exposure of the the two different tool_resources, if needed runOptions.NucleusSamplingFactor, runOptions.Stream, runOptions.MaxInputTokenCount, runOptions.MaxOutputTokenCount, runOptions.TruncationStrategy, - runOptions.ToolConstraint, runOptions.AllowParallelToolCalls, + runOptions.ModelOverride, + threadOptions.ToolResources, runOptions.ResponseFormat, - serializedAdditionalRawData: null); - return internalRequest.ToBinaryContent(); + runOptions.ToolConstraint, + additionalBinaryDataProperties: null); + return internalRequest; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/Custom/Assistants/AssistantCollectionOrder.cs b/src/Custom/Assistants/AssistantCollectionOrder.cs index 4a25b8885..275d5d98d 100644 --- a/src/Custom/Assistants/AssistantCollectionOrder.cs +++ b/src/Custom/Assistants/AssistantCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct AssistantCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static AssistantCollectionOrder Ascending { get; } = new AssistantCollectionOrder(AscendingValue); + public static AssistantCollectionOrder Ascending { get; } = new AssistantCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static AssistantCollectionOrder Descending { get; } = new AssistantCollectionOrder(DescendingValue); + public static AssistantCollectionOrder Descending { get; } = new AssistantCollectionOrder(DescValue); } diff --git a/src/Custom/Assistants/AssistantResponseFormat.cs b/src/Custom/Assistants/AssistantResponseFormat.cs index 597bbb6b4..68b9b33dc 100644 --- a/src/Custom/Assistants/AssistantResponseFormat.cs +++ b/src/Custom/Assistants/AssistantResponseFormat.cs @@ -32,8 +32,8 @@ public static AssistantResponseFormat CreateJsonSchemaFormat( InternalResponseFormatJsonSchemaJsonSchema internalSchema = new( description, name, - jsonSchema, strictSchemaEnabled, + jsonSchema, null); return new InternalAssistantResponseFormatJsonSchema(internalSchema); } diff --git a/src/Custom/Assistants/CodeInterpreterToolDefinition.Serialization.cs b/src/Custom/Assistants/CodeInterpreterToolDefinition.Serialization.cs index 208ac9240..c388480eb 100644 --- a/src/Custom/Assistants/CodeInterpreterToolDefinition.Serialization.cs +++ b/src/Custom/Assistants/CodeInterpreterToolDefinition.Serialization.cs @@ -17,7 +17,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStartObject(); writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/FileSearchRankingOptions.cs b/src/Custom/Assistants/FileSearchRankingOptions.cs index 4f39634c6..210ffe204 100644 --- a/src/Custom/Assistants/FileSearchRankingOptions.cs +++ b/src/Custom/Assistants/FileSearchRankingOptions.cs @@ -33,6 +33,6 @@ internal FileSearchRankingOptions(FileSearchRanker? ranker, float scoreThreshold { Ranker = ranker; ScoreThreshold = scoreThreshold; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; } } diff --git a/src/Custom/Assistants/FileSearchToolDefinition.Serialization.cs b/src/Custom/Assistants/FileSearchToolDefinition.Serialization.cs index ffcc62ab8..8111cc399 100644 --- a/src/Custom/Assistants/FileSearchToolDefinition.Serialization.cs +++ b/src/Custom/Assistants/FileSearchToolDefinition.Serialization.cs @@ -22,7 +22,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(_fileSearch, options); } - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/FunctionToolDefinition.Serialization.cs b/src/Custom/Assistants/FunctionToolDefinition.Serialization.cs index cafdd5d47..a209f332e 100644 --- a/src/Custom/Assistants/FunctionToolDefinition.Serialization.cs +++ b/src/Custom/Assistants/FunctionToolDefinition.Serialization.cs @@ -19,7 +19,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteObjectValue(_internalFunction, options); writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/FunctionToolDefinition.cs b/src/Custom/Assistants/FunctionToolDefinition.cs index 7ceaa6435..448cca2c4 100644 --- a/src/Custom/Assistants/FunctionToolDefinition.cs +++ b/src/Custom/Assistants/FunctionToolDefinition.cs @@ -42,7 +42,7 @@ public bool? StrictParameterSchemaEnabled } /// - /// Creates a new instance of . + /// Creates a new instance of . /// [SetsRequiredMembers] public FunctionToolDefinition(string name) @@ -53,7 +53,7 @@ public FunctionToolDefinition(string name) } /// - /// Creates a new instance of . + /// Creates a new instance of . /// public FunctionToolDefinition() : base("function") diff --git a/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs b/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs index 16dbdde59..5748a3ab3 100644 --- a/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs +++ b/src/Custom/Assistants/Internal/GeneratorStubs.Internal.cs @@ -43,7 +43,7 @@ internal partial class InternalMessageDeltaContentImageUrlObject { } internal partial class InternalMessageDeltaObjectDelta { [CodeGenMember("Role")] - internal MessageRole Role { get; } + internal MessageRole? Role { get; } } [CodeGenModel("MessageDeltaContentTextObject")] diff --git a/src/Custom/Assistants/Internal/InternalAssistantMessageClient.Protocol.cs b/src/Custom/Assistants/Internal/InternalAssistantMessageClient.Protocol.cs index fb54903bc..a83381225 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantMessageClient.Protocol.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantMessageClient.Protocol.cs @@ -23,7 +23,7 @@ public virtual async Task CreateMessageAsync(string threadId, Bina Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateMessageRequest(threadId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -42,7 +42,7 @@ public virtual ClientResult CreateMessage(string threadId, BinaryContent content Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateMessageRequest(threadId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -61,7 +61,7 @@ public virtual async Task GetMessageAsync(string threadId, string Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); using PipelineMessage message = CreateGetMessageRequest(threadId, messageId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -80,7 +80,7 @@ public virtual ClientResult GetMessage(string threadId, string messageId, Reques Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); using PipelineMessage message = CreateGetMessageRequest(threadId, messageId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -101,7 +101,7 @@ public virtual async Task ModifyMessageAsync(string threadId, stri Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyMessageRequest(threadId, messageId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -122,7 +122,7 @@ public virtual ClientResult ModifyMessage(string threadId, string messageId, Bin Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyMessageRequest(threadId, messageId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -141,7 +141,7 @@ public virtual async Task DeleteMessageAsync(string threadId, stri Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); using PipelineMessage message = CreateDeleteMessageRequest(threadId, messageId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -160,6 +160,6 @@ public virtual ClientResult DeleteMessage(string threadId, string messageId, Req Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); using PipelineMessage message = CreateDeleteMessageRequest(threadId, messageId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Assistants/Internal/InternalAssistantMessageClient.cs b/src/Custom/Assistants/Internal/InternalAssistantMessageClient.cs index e8f76476c..111dcf265 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantMessageClient.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantMessageClient.cs @@ -1,33 +1,28 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; +using System.Threading; namespace OpenAI.Assistants; [CodeGenClient("Messages")] [CodeGenSuppress("InternalAssistantMessageClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateMessageAsync", typeof(string), typeof(MessageCreationOptions))] -[CodeGenSuppress("CreateMessage", typeof(string), typeof(MessageCreationOptions))] -[CodeGenSuppress("GetMessagesAsync", typeof(string), typeof(int?), typeof(MessageCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetMessages", typeof(string), typeof(int?), typeof(MessageCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetMessageAsync", typeof(string), typeof(string))] -[CodeGenSuppress("GetMessage", typeof(string), typeof(string))] -[CodeGenSuppress("ModifyMessageAsync", typeof(string), typeof(string), typeof(MessageModificationOptions))] -[CodeGenSuppress("ModifyMessage", typeof(string), typeof(string), typeof(MessageModificationOptions))] -[CodeGenSuppress("DeleteMessageAsync", typeof(string), typeof(string))] -[CodeGenSuppress("DeleteMessage", typeof(string), typeof(string))] +[CodeGenSuppress("CreateMessageAsync", typeof(string), typeof(MessageCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateMessage", typeof(string), typeof(MessageCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("ListMessagesAsync", typeof(string), typeof(int?), typeof(MessageCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListMessages", typeof(string), typeof(int?), typeof(MessageCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetMessageAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetMessage", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ModifyMessageAsync", typeof(string), typeof(string), typeof(MessageModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("ModifyMessage", typeof(string), typeof(string), typeof(MessageModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("DeleteMessageAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("DeleteMessage", typeof(string), typeof(string), typeof(CancellationToken))] internal partial class InternalAssistantMessageClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public InternalAssistantMessageClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -37,7 +32,7 @@ internal partial class InternalAssistantMessageClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -46,7 +41,7 @@ public InternalAssistantMessageClient(ApiKeyCredential credential, OpenAIClientO Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -54,7 +49,7 @@ public InternalAssistantMessageClient(ApiKeyCredential credential, OpenAIClientO // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -63,7 +58,7 @@ protected internal InternalAssistantMessageClient(ClientPipeline pipeline, OpenA Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } } diff --git a/src/Custom/Assistants/Internal/InternalAssistantRunClient.Protocol.cs b/src/Custom/Assistants/Internal/InternalAssistantRunClient.Protocol.cs index 365bff908..86e942ae1 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantRunClient.Protocol.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantRunClient.Protocol.cs @@ -8,8 +8,8 @@ namespace OpenAI.Assistants; [CodeGenSuppress("CreateRunAsync", typeof(string), typeof(BinaryContent), typeof(IEnumerable), typeof(RequestOptions))] [CodeGenSuppress("CreateRun", typeof(string), typeof(BinaryContent), typeof(IEnumerable), typeof(RequestOptions))] -[CodeGenSuppress("GetRunStepsAsync", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(RequestOptions))] -[CodeGenSuppress("GetRunSteps", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(RequestOptions))] +[CodeGenSuppress("ListRunStepsAsync", typeof(string), typeof(string), typeof(IEnumerable), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListRunSteps", typeof(string), typeof(string), typeof(IEnumerable), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] [CodeGenSuppress("GetRunStepAsync", typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(RequestOptions))] [CodeGenSuppress("GetRunStep", typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(RequestOptions))] internal partial class InternalAssistantRunClient @@ -30,7 +30,7 @@ public virtual async Task CreateThreadAndRunAsync(BinaryContent co try { message = CreateCreateThreadAndRunRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } finally { @@ -57,7 +57,7 @@ public virtual ClientResult CreateThreadAndRun(BinaryContent content, RequestOpt try { message = CreateCreateThreadAndRunRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } finally { @@ -90,7 +90,7 @@ public virtual async Task CreateRunAsync(string threadId, BinaryCo IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; message = CreateCreateRunRequest(threadId, content, includedRunStepProperties, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } finally { @@ -123,7 +123,7 @@ public virtual ClientResult CreateRun(string threadId, BinaryContent content, Re IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; message = CreateCreateRunRequest(threadId, content, includedRunStepProperties, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } finally { @@ -150,7 +150,7 @@ public virtual async Task GetRunAsync(string threadId, string runI Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using PipelineMessage message = CreateGetRunRequest(threadId, runId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -169,7 +169,7 @@ public virtual ClientResult GetRun(string threadId, string runId, RequestOptions Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using PipelineMessage message = CreateGetRunRequest(threadId, runId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -190,7 +190,7 @@ public virtual async Task ModifyRunAsync(string threadId, string r Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyRunRequest(threadId, runId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -211,7 +211,7 @@ public virtual ClientResult ModifyRun(string threadId, string runId, BinaryConte Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyRunRequest(threadId, runId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -230,7 +230,7 @@ public virtual async Task CancelRunAsync(string threadId, string r Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using PipelineMessage message = CreateCancelRunRequest(threadId, runId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -249,7 +249,7 @@ public virtual ClientResult CancelRun(string threadId, string runId, RequestOpti Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using PipelineMessage message = CreateCancelRunRequest(threadId, runId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -275,7 +275,7 @@ public virtual async Task SubmitToolOutputsToRunAsync(string threa try { message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } finally { @@ -309,7 +309,7 @@ public virtual ClientResult SubmitToolOutputsToRun(string threadId, string runId try { message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } finally { @@ -328,8 +328,8 @@ public virtual async Task GetRunStepsAsync(string threadId, string // Always request the included properties. IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; - using PipelineMessage message = CreateGetRunStepsRequest(threadId, runId, limit, order, after, before, includedRunStepProperties, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + using PipelineMessage message = CreateListRunStepsRequest(threadId, runId, limit, order, after, before, includedRunStepProperties, options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } public virtual ClientResult GetRunSteps(string threadId, string runId, int? limit, string order, string after, string before, RequestOptions options) @@ -340,8 +340,8 @@ public virtual ClientResult GetRunSteps(string threadId, string runId, int? limi // Always request the included properties. IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; - using PipelineMessage message = CreateGetRunStepsRequest(threadId, runId, limit, order, after, before, includedRunStepProperties, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = CreateListRunStepsRequest(threadId, runId, limit, order, after, before, includedRunStepProperties, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -365,7 +365,7 @@ public virtual async Task GetRunStepAsync(string threadId, string IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; using PipelineMessage message = CreateGetRunStepRequest(threadId, runId, stepId, includedRunStepProperties, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -389,6 +389,6 @@ public virtual ClientResult GetRunStep(string threadId, string runId, string ste IEnumerable includedRunStepProperties = [InternalIncludedRunStepProperty.FileSearchResultContent]; using PipelineMessage message = CreateGetRunStepRequest(threadId, runId, stepId, includedRunStepProperties, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Assistants/Internal/InternalAssistantRunClient.cs b/src/Custom/Assistants/Internal/InternalAssistantRunClient.cs index 04384f58e..21813f852 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantRunClient.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantRunClient.cs @@ -2,41 +2,36 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; +using System.Threading; namespace OpenAI.Assistants; [CodeGenClient("Runs")] [CodeGenSuppress("InternalAssistantRunClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateThreadAndRunAsync", typeof(InternalCreateThreadAndRunRequest))] -[CodeGenSuppress("CreateThreadAndRun", typeof(InternalCreateThreadAndRunRequest))] -[CodeGenSuppress("CreateRunAsync", typeof(string), typeof(RunCreationOptions), typeof(IEnumerable))] -[CodeGenSuppress("CreateRun", typeof(string), typeof(RunCreationOptions), typeof(IEnumerable))] -[CodeGenSuppress("GetRunsAsync", typeof(string), typeof(int?), typeof(RunCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetRuns", typeof(string), typeof(int?), typeof(RunCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetRunAsync", typeof(string), typeof(string))] -[CodeGenSuppress("GetRun", typeof(string), typeof(string))] -[CodeGenSuppress("ModifyRunAsync", typeof(string), typeof(string), typeof(RunModificationOptions))] -[CodeGenSuppress("ModifyRun", typeof(string), typeof(string), typeof(RunModificationOptions))] -[CodeGenSuppress("CancelRunAsync", typeof(string), typeof(string))] -[CodeGenSuppress("CancelRun", typeof(string), typeof(string))] -[CodeGenSuppress("SubmitToolOutputsToRunAsync", typeof(string), typeof(string), typeof(InternalSubmitToolOutputsRunRequest))] -[CodeGenSuppress("SubmitToolOutputsToRun", typeof(string), typeof(string), typeof(InternalSubmitToolOutputsRunRequest))] -[CodeGenSuppress("GetRunStepsAsync", typeof(string), typeof(string), typeof(int?), typeof(RunStepCollectionOrder?), typeof(string), typeof(string), typeof(IEnumerable))] -[CodeGenSuppress("GetRunSteps", typeof(string), typeof(string), typeof(int?), typeof(RunStepCollectionOrder?), typeof(string), typeof(string), typeof(IEnumerable))] -[CodeGenSuppress("GetRunStepAsync", typeof(string), typeof(string), typeof(string), typeof(IEnumerable))] -[CodeGenSuppress("GetRunStep", typeof(string), typeof(string), typeof(string), typeof(IEnumerable))] +[CodeGenSuppress("CreateThreadAndRunAsync", typeof(InternalCreateThreadAndRunRequest), typeof(CancellationToken))] +[CodeGenSuppress("CreateThreadAndRun", typeof(InternalCreateThreadAndRunRequest), typeof(CancellationToken))] +[CodeGenSuppress("CreateRunAsync", typeof(string), typeof(RunCreationOptions), typeof(IEnumerable), typeof(CancellationToken))] +[CodeGenSuppress("CreateRun", typeof(string), typeof(RunCreationOptions), typeof(IEnumerable), typeof(CancellationToken))] +[CodeGenSuppress("ListRunsAsync", typeof(string), typeof(int?), typeof(RunCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListRuns", typeof(string), typeof(int?), typeof(RunCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetRunAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetRun", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ModifyRunAsync", typeof(string), typeof(string), typeof(RunModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("ModifyRun", typeof(string), typeof(string), typeof(RunModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CancelRunAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelRun", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("SubmitToolOutputsToRunAsync", typeof(string), typeof(string), typeof(InternalSubmitToolOutputsRunRequest), typeof(CancellationToken))] +[CodeGenSuppress("SubmitToolOutputsToRun", typeof(string), typeof(string), typeof(InternalSubmitToolOutputsRunRequest), typeof(CancellationToken))] +[CodeGenSuppress("ListRunStepsAsync", typeof(string), typeof(string), typeof(int?), typeof(RunStepCollectionOrder?), typeof(string), typeof(string), typeof(IEnumerable), typeof(CancellationToken))] +[CodeGenSuppress("ListRunSteps", typeof(string), typeof(string), typeof(int?), typeof(RunStepCollectionOrder?), typeof(string), typeof(string), typeof(IEnumerable), typeof(CancellationToken))] +[CodeGenSuppress("GetRunStepAsync", typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(CancellationToken))] +[CodeGenSuppress("GetRunStep", typeof(string), typeof(string), typeof(string), typeof(IEnumerable), typeof(CancellationToken))] internal partial class InternalAssistantRunClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public InternalAssistantRunClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -46,7 +41,7 @@ internal partial class InternalAssistantRunClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -55,7 +50,7 @@ public InternalAssistantRunClient(ApiKeyCredential credential, OpenAIClientOptio Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -63,7 +58,7 @@ public InternalAssistantRunClient(ApiKeyCredential credential, OpenAIClientOptio // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -72,7 +67,7 @@ protected internal InternalAssistantRunClient(ClientPipeline pipeline, OpenAICli Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } } diff --git a/src/Custom/Assistants/Internal/InternalAssistantThreadClient.Protocol.cs b/src/Custom/Assistants/Internal/InternalAssistantThreadClient.Protocol.cs index 3986d26c8..770d07671 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantThreadClient.Protocol.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantThreadClient.Protocol.cs @@ -18,7 +18,7 @@ internal partial class InternalAssistantThreadClient public virtual async Task CreateThreadAsync(BinaryContent content, RequestOptions options = null) { using PipelineMessage message = CreateCreateThreadRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -32,7 +32,7 @@ public virtual async Task CreateThreadAsync(BinaryContent content, public virtual ClientResult CreateThread(BinaryContent content, RequestOptions options = null) { using PipelineMessage message = CreateCreateThreadRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -49,7 +49,7 @@ public virtual async Task GetThreadAsync(string threadId, RequestO Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); using PipelineMessage message = CreateGetThreadRequest(threadId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -66,7 +66,7 @@ public virtual ClientResult GetThread(string threadId, RequestOptions options) Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); using PipelineMessage message = CreateGetThreadRequest(threadId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -85,7 +85,7 @@ public virtual async Task ModifyThreadAsync(string threadId, Binar Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyThreadRequest(threadId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -104,7 +104,7 @@ public virtual ClientResult ModifyThread(string threadId, BinaryContent content, Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyThreadRequest(threadId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -121,7 +121,7 @@ public virtual async Task DeleteThreadAsync(string threadId, Reque Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); using PipelineMessage message = CreateDeleteThreadRequest(threadId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -138,6 +138,6 @@ public virtual ClientResult DeleteThread(string threadId, RequestOptions options Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); using PipelineMessage message = CreateDeleteThreadRequest(threadId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Assistants/Internal/InternalAssistantThreadClient.cs b/src/Custom/Assistants/Internal/InternalAssistantThreadClient.cs index f0cb90c9a..799bd1121 100644 --- a/src/Custom/Assistants/Internal/InternalAssistantThreadClient.cs +++ b/src/Custom/Assistants/Internal/InternalAssistantThreadClient.cs @@ -1,31 +1,26 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; +using System.Threading; namespace OpenAI.Assistants; [CodeGenClient("Threads")] [CodeGenSuppress("InternalAssistantThreadClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateThreadAsync", typeof(ThreadCreationOptions))] -[CodeGenSuppress("CreateThread", typeof(ThreadCreationOptions))] -[CodeGenSuppress("GetThreadAsync", typeof(string))] -[CodeGenSuppress("GetThread", typeof(string))] -[CodeGenSuppress("ModifyThreadAsync", typeof(string), typeof(ThreadModificationOptions))] -[CodeGenSuppress("ModifyThread", typeof(string), typeof(ThreadModificationOptions))] -[CodeGenSuppress("DeleteThreadAsync", typeof(string))] -[CodeGenSuppress("DeleteThread", typeof(string))] +[CodeGenSuppress("CreateThreadAsync", typeof(ThreadCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateThread", typeof(ThreadCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("GetThreadAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetThread", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ModifyThreadAsync", typeof(string), typeof(ThreadModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("ModifyThread", typeof(string), typeof(ThreadModificationOptions), typeof(CancellationToken))] +[CodeGenSuppress("DeleteThreadAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("DeleteThread", typeof(string), typeof(CancellationToken))] internal partial class InternalAssistantThreadClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public InternalAssistantThreadClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -35,7 +30,7 @@ internal partial class InternalAssistantThreadClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -44,7 +39,7 @@ public InternalAssistantThreadClient(ApiKeyCredential credential, OpenAIClientOp Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -52,7 +47,7 @@ public InternalAssistantThreadClient(ApiKeyCredential credential, OpenAIClientOp // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -61,7 +56,7 @@ protected internal InternalAssistantThreadClient(ClientPipeline pipeline, OpenAI Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } } diff --git a/src/Custom/Assistants/Internal/InternalMessageImageFileContent.Serialization.cs b/src/Custom/Assistants/Internal/InternalMessageImageFileContent.Serialization.cs index 1cd98176f..748340361 100644 --- a/src/Custom/Assistants/Internal/InternalMessageImageFileContent.Serialization.cs +++ b/src/Custom/Assistants/Internal/InternalMessageImageFileContent.Serialization.cs @@ -19,7 +19,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStringValue(_type); writer.WritePropertyName("image_file"u8); writer.WriteObjectValue(_imageFile, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/Internal/InternalMessageImageUrlContent.Serialization.cs b/src/Custom/Assistants/Internal/InternalMessageImageUrlContent.Serialization.cs index 2a4eb69cc..44055a32f 100644 --- a/src/Custom/Assistants/Internal/InternalMessageImageUrlContent.Serialization.cs +++ b/src/Custom/Assistants/Internal/InternalMessageImageUrlContent.Serialization.cs @@ -19,7 +19,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStringValue(_type); writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(_imageUrl, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } \ No newline at end of file diff --git a/src/Custom/Assistants/Internal/InternalRequestMessageTextContent.Serialization.cs b/src/Custom/Assistants/Internal/InternalRequestMessageTextContent.Serialization.cs index 931aed080..16c7e9356 100644 --- a/src/Custom/Assistants/Internal/InternalRequestMessageTextContent.Serialization.cs +++ b/src/Custom/Assistants/Internal/InternalRequestMessageTextContent.Serialization.cs @@ -19,7 +19,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStringValue(Type.ToString()); writer.WritePropertyName("text"u8); writer.WriteStringValue(InternalText); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/Internal/InternalResponseMessageTextContent.Serialization.cs b/src/Custom/Assistants/Internal/InternalResponseMessageTextContent.Serialization.cs index 0b1f5487a..e798a79e2 100644 --- a/src/Custom/Assistants/Internal/InternalResponseMessageTextContent.Serialization.cs +++ b/src/Custom/Assistants/Internal/InternalResponseMessageTextContent.Serialization.cs @@ -19,7 +19,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStringValue(_type); writer.WritePropertyName("text"u8); writer.WriteObjectValue(_text, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/Internal/Pagination/AssistantCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/AssistantCollectionResult.cs index 9967fdb00..5e85eb83a 100644 --- a/src/Custom/Assistants/Internal/Pagination/AssistantCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/AssistantCollectionResult.cs @@ -90,7 +90,7 @@ public static bool HasNextPage(ClientResult result) internal virtual ClientResult GetAssistants(int? limit, string? order, string? after, string? before, RequestOptions? options) { - using PipelineMessage message = _assistantClient.CreateGetAssistantsRequest(limit, order, after, before, options); + using PipelineMessage message = _assistantClient.CreateListAssistantsRequest(limit, order, after, before, options); return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Assistants/Internal/Pagination/AsyncAssistantCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/AsyncAssistantCollectionResult.cs index 09e446308..0ea0acc03 100644 --- a/src/Custom/Assistants/Internal/Pagination/AsyncAssistantCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/AsyncAssistantCollectionResult.cs @@ -89,7 +89,7 @@ public static bool HasNextPage(ClientResult result) internal virtual async Task GetAssistantsAsync(int? limit, string? order, string? after, string? before, RequestOptions? options) { - using PipelineMessage message = _assistantClient.CreateGetAssistantsRequest(limit, order, after, before, options); + using PipelineMessage message = _assistantClient.CreateListAssistantsRequest(limit, order, after, before, options); return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } } diff --git a/src/Custom/Assistants/Internal/Pagination/AsyncMessageCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/AsyncMessageCollectionResult.cs index dc23d3221..4f9c4c0a0 100644 --- a/src/Custom/Assistants/Internal/Pagination/AsyncMessageCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/AsyncMessageCollectionResult.cs @@ -67,7 +67,7 @@ protected override IAsyncEnumerable GetValuesFromPageAsync(Client } public async Task GetFirstPageAsync() - => await _messageClient.GetMessagesAsync(_threadId, _limit, _order, _after, _before, _options).ConfigureAwait(false); + => await _messageClient.ListMessagesAsync(_threadId, _limit, _order, _after, _before, _options).ConfigureAwait(false); public async Task GetNextPageAsync(ClientResult result) { @@ -78,7 +78,7 @@ public async Task GetNextPageAsync(ClientResult result) using JsonDocument doc = JsonDocument.Parse(response.Content); string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!; - return await _messageClient.GetMessagesAsync(_threadId, _limit, _order, lastId, _before, _options).ConfigureAwait(false); + return await _messageClient.ListMessagesAsync(_threadId, _limit, _order, lastId, _before, _options).ConfigureAwait(false); } public static bool HasNextPage(ClientResult result) diff --git a/src/Custom/Assistants/Internal/Pagination/AsyncRunCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/AsyncRunCollectionResult.cs index 1a8250935..4bccb7501 100644 --- a/src/Custom/Assistants/Internal/Pagination/AsyncRunCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/AsyncRunCollectionResult.cs @@ -66,7 +66,7 @@ protected override IAsyncEnumerable GetValuesFromPageAsync(ClientResu } public async Task GetFirstPageAsync() - => await _runClient.GetRunsAsync(_threadId, _limit, _order, _after, _before, _options).ConfigureAwait(false); + => await _runClient.ListRunsAsync(_threadId, _limit, _order, _after, _before, _options).ConfigureAwait(false); public async Task GetNextPageAsync(ClientResult result) { @@ -77,7 +77,7 @@ public async Task GetNextPageAsync(ClientResult result) using JsonDocument doc = JsonDocument.Parse(response.Content); string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!; - return await _runClient.GetRunsAsync(_threadId, _limit, _order, lastId, _before, _options).ConfigureAwait(false); + return await _runClient.ListRunsAsync(_threadId, _limit, _order, lastId, _before, _options).ConfigureAwait(false); } public static bool HasNextPage(ClientResult result) diff --git a/src/Custom/Assistants/Internal/Pagination/MessageCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/MessageCollectionResult.cs index d6803ae71..5982fab53 100644 --- a/src/Custom/Assistants/Internal/Pagination/MessageCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/MessageCollectionResult.cs @@ -63,7 +63,7 @@ protected override IEnumerable GetValuesFromPage(ClientResult pag } public ClientResult GetFirstPage() - => _messageClient.GetMessages(_threadId, _limit, _order, _after, _before, _options); + => _messageClient.ListMessages(_threadId, _limit, _order, _after, _before, _options); public ClientResult GetNextPage(ClientResult result) { @@ -74,7 +74,7 @@ public ClientResult GetNextPage(ClientResult result) using JsonDocument doc = JsonDocument.Parse(response.Content); string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!; - return _messageClient.GetMessages(_threadId, _limit, _order, lastId, _before, _options); + return _messageClient.ListMessages(_threadId, _limit, _order, lastId, _before, _options); } public static bool HasNextPage(ClientResult result) diff --git a/src/Custom/Assistants/Internal/Pagination/RunCollectionResult.cs b/src/Custom/Assistants/Internal/Pagination/RunCollectionResult.cs index f7e53c921..9bf331a30 100644 --- a/src/Custom/Assistants/Internal/Pagination/RunCollectionResult.cs +++ b/src/Custom/Assistants/Internal/Pagination/RunCollectionResult.cs @@ -62,7 +62,7 @@ protected override IEnumerable GetValuesFromPage(ClientResult page) } public ClientResult GetFirstPage() - => _runClient.GetRuns(_threadId, _limit, _order, _after, _before, _options); + => _runClient.ListRuns(_threadId, _limit, _order, _after, _before, _options); public ClientResult GetNextPage(ClientResult result) { @@ -73,7 +73,7 @@ public ClientResult GetNextPage(ClientResult result) using JsonDocument doc = JsonDocument.Parse(response.Content); string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!; - return _runClient.GetRuns(_threadId, _limit, _order, lastId, _before, _options); + return _runClient.ListRuns(_threadId, _limit, _order, lastId, _before, _options); } public static bool HasNextPage(ClientResult result) diff --git a/src/Custom/Assistants/Internal/UnknownAssistantToolDefinition.Serialization.cs b/src/Custom/Assistants/Internal/UnknownAssistantToolDefinition.Serialization.cs index 26f4e5baa..22c7d878a 100644 --- a/src/Custom/Assistants/Internal/UnknownAssistantToolDefinition.Serialization.cs +++ b/src/Custom/Assistants/Internal/UnknownAssistantToolDefinition.Serialization.cs @@ -17,7 +17,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteStartObject(); writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Assistants/MessageCollectionOrder.cs b/src/Custom/Assistants/MessageCollectionOrder.cs index aa8d4444c..47d03e935 100644 --- a/src/Custom/Assistants/MessageCollectionOrder.cs +++ b/src/Custom/Assistants/MessageCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct MessageCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static MessageCollectionOrder Ascending { get; } = new MessageCollectionOrder(AscendingValue); + public static MessageCollectionOrder Ascending { get; } = new MessageCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static MessageCollectionOrder Descending { get; } = new MessageCollectionOrder(DescendingValue); + public static MessageCollectionOrder Descending { get; } = new MessageCollectionOrder(DescValue); } diff --git a/src/Custom/Assistants/MessageCreationAttachment.cs b/src/Custom/Assistants/MessageCreationAttachment.cs index d3409532f..c75d00c7b 100644 --- a/src/Custom/Assistants/MessageCreationAttachment.cs +++ b/src/Custom/Assistants/MessageCreationAttachment.cs @@ -1,6 +1,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Text.Json; namespace OpenAI.Assistants; @@ -39,7 +40,7 @@ private static void DeserializeTools(JsonProperty property, ref IReadOnlyList deserializedTools = []; foreach (JsonElement toolElement in property.Value.EnumerateArray()) { - deserializedTools.Add(ToolDefinition.DeserializeToolDefinition(toolElement)); + deserializedTools.Add(ToolDefinition.DeserializeToolDefinition(toolElement, ModelSerializationExtensions.WireOptions)); } tools = deserializedTools; } diff --git a/src/Custom/Assistants/MessageCreationOptions.cs b/src/Custom/Assistants/MessageCreationOptions.cs index fc256245a..676ac91fc 100644 --- a/src/Custom/Assistants/MessageCreationOptions.cs +++ b/src/Custom/Assistants/MessageCreationOptions.cs @@ -29,10 +29,10 @@ public partial class MessageCreationOptions /// public MessageCreationOptions() : this( - MessageRole.User, - new ChangeTrackingList(), new ChangeTrackingList(), new ChangeTrackingDictionary(), + MessageRole.User, + new ChangeTrackingList(), new ChangeTrackingDictionary()) { } diff --git a/src/Custom/Assistants/RunCollectionOrder.cs b/src/Custom/Assistants/RunCollectionOrder.cs index db99d10b9..0b2f91749 100644 --- a/src/Custom/Assistants/RunCollectionOrder.cs +++ b/src/Custom/Assistants/RunCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct RunCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static RunCollectionOrder Ascending { get; } = new RunCollectionOrder(AscendingValue); + public static RunCollectionOrder Ascending { get; } = new RunCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static RunCollectionOrder Descending { get; } = new RunCollectionOrder(DescendingValue); + public static RunCollectionOrder Descending { get; } = new RunCollectionOrder(DescValue); } diff --git a/src/Custom/Assistants/RunIncompleteReason.cs b/src/Custom/Assistants/RunIncompleteReason.cs index 5b17c95d0..692300ebf 100644 --- a/src/Custom/Assistants/RunIncompleteReason.cs +++ b/src/Custom/Assistants/RunIncompleteReason.cs @@ -11,10 +11,10 @@ public readonly partial struct RunIncompleteReason { // CUSTOM: Renamed. [CodeGenMember("MaxCompletionTokens")] - public static RunIncompleteReason MaxOutputTokenCount { get; } = new RunIncompleteReason(MaxOutputTokenCountValue); + public static RunIncompleteReason MaxOutputTokenCount { get; } = new RunIncompleteReason(MaxCompletionTokensValue); // CUSTOM: Renamed. [CodeGenMember("MaxPromptTokens")] - public static RunIncompleteReason MaxInputTokenCount { get; } = new RunIncompleteReason(MaxInputTokenCountValue); + public static RunIncompleteReason MaxInputTokenCount { get; } = new RunIncompleteReason(MaxPromptTokensValue); } } diff --git a/src/Custom/Assistants/RunStepCollectionOrder.cs b/src/Custom/Assistants/RunStepCollectionOrder.cs index e7011053d..5cc86bd75 100644 --- a/src/Custom/Assistants/RunStepCollectionOrder.cs +++ b/src/Custom/Assistants/RunStepCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct RunStepCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static RunStepCollectionOrder Ascending { get; } = new RunStepCollectionOrder(AscendingValue); + public static RunStepCollectionOrder Ascending { get; } = new RunStepCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static RunStepCollectionOrder Descending { get; } = new RunStepCollectionOrder(DescendingValue); + public static RunStepCollectionOrder Descending { get; } = new RunStepCollectionOrder(DescValue); } diff --git a/src/Custom/Assistants/RunTruncationStrategy.cs b/src/Custom/Assistants/RunTruncationStrategy.cs index d4328f349..fe895710d 100644 --- a/src/Custom/Assistants/RunTruncationStrategy.cs +++ b/src/Custom/Assistants/RunTruncationStrategy.cs @@ -10,38 +10,6 @@ namespace OpenAI.Assistants [CodeGenSuppress(nameof(RunTruncationStrategy), typeof(InternalTruncationObjectType))] public partial class RunTruncationStrategy { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. [CodeGenMember("Type")] internal readonly InternalTruncationObjectType _type; @@ -56,7 +24,7 @@ public partial class RunTruncationStrategy /// The default that will eliminate messages in the middle of the thread /// to fit within the context length of the model or the max prompt tokens. /// - public static RunTruncationStrategy Auto { get; } = new(InternalTruncationObjectType.Auto, 0, null); + public static RunTruncationStrategy Auto { get; } = new(0, InternalTruncationObjectType.Auto, null); /// /// Creates a new instance using the last_messages strategy type, @@ -65,6 +33,6 @@ public partial class RunTruncationStrategy /// The count of last messages that the run should evaluate. /// public static RunTruncationStrategy CreateLastMessagesStrategy(int lastMessageCount) - => new(InternalTruncationObjectType.LastMessages, lastMessageCount, null); + => new(lastMessageCount, InternalTruncationObjectType.LastMessages, null); } } diff --git a/src/Custom/Assistants/Streaming/RequiredActionUpdate.cs b/src/Custom/Assistants/Streaming/RequiredActionUpdate.cs index bfebfe8b9..8a6a9d805 100644 --- a/src/Custom/Assistants/Streaming/RequiredActionUpdate.cs +++ b/src/Custom/Assistants/Streaming/RequiredActionUpdate.cs @@ -43,7 +43,7 @@ internal RequiredActionUpdate(ThreadRun run, RequiredAction action) internal static IEnumerable DeserializeRequiredActionUpdates(JsonElement element) { - ThreadRun run = ThreadRun.DeserializeThreadRun(element); + ThreadRun run = ThreadRun.DeserializeThreadRun(element, ModelSerializationExtensions.WireOptions); List updates = []; foreach (RequiredAction action in run.RequiredActions ?? []) { diff --git a/src/Custom/Assistants/ThreadInitializationMessage.cs b/src/Custom/Assistants/ThreadInitializationMessage.cs index bcae23ac5..9fd846fa7 100644 --- a/src/Custom/Assistants/ThreadInitializationMessage.cs +++ b/src/Custom/Assistants/ThreadInitializationMessage.cs @@ -18,7 +18,7 @@ public ThreadInitializationMessage(MessageRole role, IEnumerable } internal ThreadInitializationMessage(MessageCreationOptions baseOptions) - : base(baseOptions.Role, baseOptions.Content, baseOptions.Attachments, baseOptions.Metadata, null) + : base(baseOptions.Attachments, baseOptions.Metadata, baseOptions.Role, baseOptions.Content, null) { } /// diff --git a/src/Custom/Assistants/ThreadRun.cs b/src/Custom/Assistants/ThreadRun.cs index 0d8a04fed..6b7c41d51 100644 --- a/src/Custom/Assistants/ThreadRun.cs +++ b/src/Custom/Assistants/ThreadRun.cs @@ -66,7 +66,7 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string /// is the abstract base type for all required actions. Its /// concrete type can be one of: /// - /// + /// /// /// public IReadOnlyList RequiredActions => _internalRequiredAction?.SubmitToolOutputs?.ToolCalls ?? []; @@ -87,7 +87,7 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string public float? NucleusSamplingFactor { get; } /// - /// Whether parallel function calling is enabled during tool use for the thread. + /// Whether parallel function calling is enabled during tool use for the thread. /// /// /// Assumed true if not otherwise specified. diff --git a/src/Custom/Assistants/ToolConstraint.cs b/src/Custom/Assistants/ToolConstraint.cs index b333236f8..e19da8e75 100644 --- a/src/Custom/Assistants/ToolConstraint.cs +++ b/src/Custom/Assistants/ToolConstraint.cs @@ -12,7 +12,6 @@ public partial class ToolConstraint [CodeGenMember("Type")] private readonly string _objectType; private readonly string _objectFunctionName; - private readonly IDictionary SerializedAdditionalRawData; // CUSTOM: Made internal. /// Gets or sets the function. diff --git a/src/Custom/Assistants/ToolDefinition.cs b/src/Custom/Assistants/ToolDefinition.cs index cca50418d..020c861bd 100644 --- a/src/Custom/Assistants/ToolDefinition.cs +++ b/src/Custom/Assistants/ToolDefinition.cs @@ -28,4 +28,9 @@ protected ToolDefinition(string type) { Type = type; } + + // Backcompat with the old codegen. + protected ToolDefinition() + { + } } diff --git a/src/Custom/Audio/AudioClient.Protocol.cs b/src/Custom/Audio/AudioClient.Protocol.cs index 0fd68c698..32e71831d 100644 --- a/src/Custom/Audio/AudioClient.Protocol.cs +++ b/src/Custom/Audio/AudioClient.Protocol.cs @@ -32,7 +32,7 @@ public virtual async Task GenerateSpeechAsync(BinaryContent conten Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateSpeechRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -53,7 +53,7 @@ public virtual ClientResult GenerateSpeech(BinaryContent content, RequestOptions Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateSpeechRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } // CUSTOM: @@ -78,7 +78,7 @@ public virtual async Task TranscribeAudioAsync(BinaryContent conte Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateTranscriptionRequest(content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -103,7 +103,7 @@ public virtual ClientResult TranscribeAudio(BinaryContent content, string conten Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateTranscriptionRequest(content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } // CUSTOM: @@ -127,7 +127,7 @@ public virtual async Task TranslateAudioAsync(BinaryContent conten Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateTranslationRequest(content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -151,6 +151,6 @@ public virtual ClientResult TranslateAudio(BinaryContent content, string content Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateTranslationRequest(content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } \ No newline at end of file diff --git a/src/Custom/Audio/AudioClient.cs b/src/Custom/Audio/AudioClient.cs index fbe3e0c30..8dd2e7efe 100644 --- a/src/Custom/Audio/AudioClient.cs +++ b/src/Custom/Audio/AudioClient.cs @@ -14,24 +14,14 @@ namespace OpenAI.Audio; /// The service client for OpenAI audio operations. [CodeGenClient("Audio")] [CodeGenSuppress("AudioClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateSpeechAsync", typeof(SpeechGenerationOptions))] -[CodeGenSuppress("CreateSpeech", typeof(SpeechGenerationOptions))] -[CodeGenSuppress("CreateTranscriptionAsync", typeof(AudioTranscriptionOptions))] -[CodeGenSuppress("CreateTranscription", typeof(AudioTranscriptionOptions))] -[CodeGenSuppress("CreateTranslationAsync", typeof(AudioTranslationOptions))] -[CodeGenSuppress("CreateTranslation", typeof(AudioTranslationOptions))] +[CodeGenSuppress("CreateSpeechAsync", typeof(SpeechGenerationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateSpeech", typeof(SpeechGenerationOptions), typeof(CancellationToken))] public partial class AudioClient { private readonly string _model; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -44,7 +34,7 @@ public partial class AudioClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -57,7 +47,7 @@ public partial class AudioClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -70,7 +60,7 @@ public AudioClient(string model, ApiKeyCredential credential, OpenAIClientOption options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -79,7 +69,7 @@ public AudioClient(string model, ApiKeyCredential credential, OpenAIClientOption // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -92,7 +82,7 @@ protected internal AudioClient(ClientPipeline pipeline, string model, OpenAIClie options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } @@ -116,7 +106,7 @@ public virtual async Task> GenerateSpeechAsync(string t options ??= new(); CreateSpeechGenerationOptions(text, voice, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateSpeechAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse()); } @@ -139,7 +129,7 @@ public virtual ClientResult GenerateSpeech(string text, GeneratedSpe options ??= new(); CreateSpeechGenerationOptions(text, voice, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateSpeech(content, cancellationToken.ToRequestOptions()); ; return ClientResult.FromValue(result.GetRawResponse().Content, result.GetRawResponse()); } diff --git a/src/Custom/Audio/AudioTranscription.Serialization.cs b/src/Custom/Audio/AudioTranscription.Serialization.cs index 0e73332c6..28b1538eb 100644 --- a/src/Custom/Audio/AudioTranscription.Serialization.cs +++ b/src/Custom/Audio/AudioTranscription.Serialization.cs @@ -20,10 +20,10 @@ internal static AudioTranscription FromResponse(PipelineResponse response) text: response.Content?.ToString(), words: new ChangeTrackingList(), segments: new ChangeTrackingList(), - serializedAdditionalRawData: new Dictionary()); + additionalBinaryDataProperties: new Dictionary()); } using var document = JsonDocument.Parse(response.Content); - return DeserializeAudioTranscription(document.RootElement); + return DeserializeAudioTranscription(document.RootElement, null); } } diff --git a/src/Custom/Audio/AudioTranscriptionFormat.cs b/src/Custom/Audio/AudioTranscriptionFormat.cs index d1096cfa9..d5a3aca55 100644 --- a/src/Custom/Audio/AudioTranscriptionFormat.cs +++ b/src/Custom/Audio/AudioTranscriptionFormat.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel; namespace OpenAI.Audio; @@ -11,25 +10,25 @@ public readonly partial struct AudioTranscriptionFormat /// Plain text only. [EditorBrowsable(EditorBrowsableState.Never)] [CodeGenMember("Text")] - public static AudioTranscriptionFormat Text { get; } = new(TextValue); + public static AudioTranscriptionFormat Text { get; } = new AudioTranscriptionFormat(TextValue); // CUSTOM: Rename, reflecting convergence with Text /// Plain text only. [CodeGenMember("Json")] - public static AudioTranscriptionFormat Simple { get; } = new(SimpleValue); + public static AudioTranscriptionFormat Simple { get; } = new AudioTranscriptionFormat(JsonValue); // CUSTOM: Rename. /// Plain text provided with additional metadata, such as duration and timestamps. [CodeGenMember("VerboseJson")] - public static AudioTranscriptionFormat Verbose { get; } = new(VerboseValue); + public static AudioTranscriptionFormat Verbose { get; } = new AudioTranscriptionFormat(VerboseJsonValue); // CUSTOM: Added custom doc comments. /// Text formatted as SubRip (.srt) file. [CodeGenMember("Srt")] - public static AudioTranscriptionFormat Srt { get; } = new(SrtValue); + public static AudioTranscriptionFormat Srt { get; } = new AudioTranscriptionFormat(SrtValue); // CUSTOM: Added custom doc comments. /// Text formatted as a Web Video Text Tracks, a.k.a. WebVTT, (.vtt) file. [CodeGenMember("Vtt")] - public static AudioTranscriptionFormat Vtt { get; } = new(VttValue); + public static AudioTranscriptionFormat Vtt { get; } = new AudioTranscriptionFormat(VttValue); } \ No newline at end of file diff --git a/src/Custom/Audio/AudioTranslation.Serialization.cs b/src/Custom/Audio/AudioTranslation.Serialization.cs index a2ac14d57..3eeed49f1 100644 --- a/src/Custom/Audio/AudioTranslation.Serialization.cs +++ b/src/Custom/Audio/AudioTranslation.Serialization.cs @@ -19,10 +19,10 @@ internal static AudioTranslation FromResponse(PipelineResponse response) duration: null, text: response.Content?.ToString(), segments: new ChangeTrackingList(), - serializedAdditionalRawData: new Dictionary()); + additionalBinaryDataProperties: new Dictionary()); } using var document = JsonDocument.Parse(response.Content); - return DeserializeAudioTranslation(document.RootElement); + return DeserializeAudioTranslation(document.RootElement, null); } } diff --git a/src/Custom/Audio/AudioTranslationFormat.cs b/src/Custom/Audio/AudioTranslationFormat.cs index 33f8cbf56..969a65413 100644 --- a/src/Custom/Audio/AudioTranslationFormat.cs +++ b/src/Custom/Audio/AudioTranslationFormat.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel; namespace OpenAI.Audio; @@ -11,25 +10,25 @@ public readonly partial struct AudioTranslationFormat /// Plain text only. [EditorBrowsable(EditorBrowsableState.Never)] [CodeGenMember("Text")] - public static AudioTranslationFormat Text { get; } = new(TextValue); + public static AudioTranslationFormat Text { get; } = new AudioTranslationFormat(TextValue); // CUSTOM: Rename, reflecting convergence with Text /// Plain text only. [CodeGenMember("Json")] - public static AudioTranslationFormat Simple { get; } = new(SimpleValue); + public static AudioTranslationFormat Simple { get; } = new AudioTranslationFormat(JsonValue); // CUSTOM: Rename. /// Plain text provided with additional metadata, such as duration and timestamps. [CodeGenMember("VerboseJson")] - public static AudioTranslationFormat Verbose { get; } = new(VerboseValue); + public static AudioTranslationFormat Verbose { get; } = new AudioTranslationFormat(VerboseJsonValue); // CUSTOM: Added custom doc comments. /// Text formatted as SubRip (.srt) file. [CodeGenMember("Srt")] - public static AudioTranslationFormat Srt { get; } = new(SrtValue); + public static AudioTranslationFormat Srt { get; } = new AudioTranslationFormat(SrtValue); // CUSTOM: Added custom doc comments. /// Text formatted as a Web Video Text Tracks, a.k.a. WebVTT, (.vtt) file. [CodeGenMember("Vtt")] - public static AudioTranslationFormat Vtt { get; } = new(VttValue); + public static AudioTranslationFormat Vtt { get; } = new AudioTranslationFormat(VttValue); } \ No newline at end of file diff --git a/src/Custom/Audio/OpenAIAudioModelFactory.cs b/src/Custom/Audio/OpenAIAudioModelFactory.cs index f854dc3a3..79fb03a86 100644 --- a/src/Custom/Audio/OpenAIAudioModelFactory.cs +++ b/src/Custom/Audio/OpenAIAudioModelFactory.cs @@ -15,13 +15,13 @@ public static AudioTranscription AudioTranscription(string language = null, Time segments ??= new List(); return new AudioTranscription( - InternalCreateTranscriptionResponseVerboseJsonTask.Transcribe, language, - duration, text, words.ToList(), segments.ToList(), - serializedAdditionalRawData: null); + InternalCreateTranscriptionResponseVerboseJsonTask.Transcribe, + duration, + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -31,12 +31,12 @@ public static AudioTranslation AudioTranslation(string language = null, TimeSpan segments ??= new List(); return new AudioTranslation( - InternalCreateTranslationResponseVerboseJsonTask.Translate, language, - duration, text, - segments.ToList(), - serializedAdditionalRawData: null); + segments: segments.ToList(), + task: InternalCreateTranslationResponseVerboseJsonTask.Translate, + duration, + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -45,16 +45,16 @@ public static TranscribedSegment TranscribedSegment(int id = default, int seekOf { return new TranscribedSegment( id, - seekOffset, + text, + temperature, + compressionRatio, startTime, endTime, - text, + seekOffset, tokenIds, - temperature, averageLogProbability, - compressionRatio, noSpeechProbability, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -65,6 +65,6 @@ public static TranscribedWord TranscribedWord(string word = null, TimeSpan start word, startTime, endTime, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } } diff --git a/src/Custom/Audio/TranscribedSegment.cs b/src/Custom/Audio/TranscribedSegment.cs index e71554a91..ab11007c3 100644 --- a/src/Custom/Audio/TranscribedSegment.cs +++ b/src/Custom/Audio/TranscribedSegment.cs @@ -9,9 +9,6 @@ namespace OpenAI.Audio; [StructLayout(LayoutKind.Auto)] public readonly partial struct TranscribedSegment { - // CUSTOM: Remove setter. Auto-implemented instance properties in readonly structs must be readonly. - internal IDictionary SerializedAdditionalRawData { get; } - // CUSTOM: Renamed. /// The start time of the segment. [CodeGenMember("Start")] diff --git a/src/Custom/Audio/TranscribedWord.cs b/src/Custom/Audio/TranscribedWord.cs index fcd0bcab3..5b0d76c4f 100644 --- a/src/Custom/Audio/TranscribedWord.cs +++ b/src/Custom/Audio/TranscribedWord.cs @@ -9,9 +9,6 @@ namespace OpenAI.Audio; [StructLayout(LayoutKind.Auto)] public readonly partial struct TranscribedWord { - // CUSTOM: Remove setter. Auto-implemented instance properties in readonly structs must be readonly. - internal IDictionary SerializedAdditionalRawData { get; } - // CUSTOM: Renamed. /// The start time of the word. [CodeGenMember("Start")] diff --git a/src/Custom/Batch/BatchClient.Protocol.cs b/src/Custom/Batch/BatchClient.Protocol.cs index 3bcf065f6..bdeab40cf 100644 --- a/src/Custom/Batch/BatchClient.Protocol.cs +++ b/src/Custom/Batch/BatchClient.Protocol.cs @@ -8,6 +8,8 @@ namespace OpenAI.Batch; [CodeGenSuppress("RetrieveBatch", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("RetrieveBatchAsync", typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListBatches", typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListBatchesAsync", typeof(string), typeof(int?), typeof(RequestOptions))] public partial class BatchClient { /// @@ -29,7 +31,7 @@ public virtual async Task CreateBatchAsync(BinaryContent c using PipelineMessage message = CreateCreateBatchRequest(content, options); - PipelineResponse response = await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); + PipelineResponse response = await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); using JsonDocument doc = JsonDocument.Parse(response.Content); string batchId = doc.RootElement.GetProperty("id"u8).GetString(); @@ -57,7 +59,7 @@ public virtual CreateBatchOperation CreateBatch(BinaryContent content, bool wait Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateBatchRequest(content, options); - PipelineResponse response = _pipeline.ProcessMessage(message, options); + PipelineResponse response = Pipeline.ProcessMessage(message, options); using JsonDocument doc = JsonDocument.Parse(response.Content); string batchId = doc.RootElement.GetProperty("id"u8).GetString(); @@ -77,7 +79,7 @@ public virtual CreateBatchOperation CreateBatch(BinaryContent content, bool wait /// The response returned from the service. public virtual AsyncCollectionResult GetBatchesAsync(string after, int? limit, RequestOptions options) { - return new AsyncBatchCollectionResult(this, _pipeline, options, limit, after); + return new AsyncBatchCollectionResult(this, Pipeline, options, limit, after); } /// @@ -90,7 +92,7 @@ public virtual AsyncCollectionResult GetBatchesAsync(string after, int? limit, R /// The response returned from the service. public virtual CollectionResult GetBatches(string after, int? limit, RequestOptions options) { - return new BatchCollectionResult(this, _pipeline, options, limit, after); + return new BatchCollectionResult(this, Pipeline, options, limit, after); } /// @@ -107,7 +109,7 @@ internal virtual async Task GetBatchAsync(string batchId, RequestO Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateRetrieveBatchRequest(batchId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -124,12 +126,12 @@ internal virtual ClientResult GetBatch(string batchId, RequestOptions options) Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateRetrieveBatchRequest(batchId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } internal virtual PipelineMessage CreateCreateBatchRequest(BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -146,7 +148,7 @@ internal virtual PipelineMessage CreateCreateBatchRequest(BinaryContent content, internal virtual PipelineMessage CreateGetBatchesRequest(string after, int? limit, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -169,7 +171,7 @@ internal virtual PipelineMessage CreateGetBatchesRequest(string after, int? limi internal virtual PipelineMessage CreateRetrieveBatchRequest(string batchId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -185,7 +187,7 @@ internal virtual PipelineMessage CreateRetrieveBatchRequest(string batchId, Requ internal virtual PipelineMessage CreateCancelBatchRequest(string batchId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; diff --git a/src/Custom/Batch/BatchClient.cs b/src/Custom/Batch/BatchClient.cs index 6e114d12f..c6f6fd867 100644 --- a/src/Custom/Batch/BatchClient.cs +++ b/src/Custom/Batch/BatchClient.cs @@ -3,6 +3,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Threading; namespace OpenAI.Batch; @@ -14,28 +15,22 @@ namespace OpenAI.Batch; [Experimental("OPENAI001")] [CodeGenClient("Batches")] [CodeGenSuppress("BatchClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateBatch", typeof(string), typeof(InternalCreateBatchRequestEndpoint), typeof(InternalBatchCompletionTimeframe), typeof(IReadOnlyDictionary))] -[CodeGenSuppress("CreateBatchAsync", typeof(string), typeof(InternalCreateBatchRequestEndpoint), typeof(InternalBatchCompletionTimeframe), typeof(IReadOnlyDictionary))] +[CodeGenSuppress("CreateBatch", typeof(string), typeof(InternalCreateBatchRequestEndpoint), typeof(InternalBatchCompletionTimeframe), typeof(IDictionary), typeof(CancellationToken))] +[CodeGenSuppress("CreateBatchAsync", typeof(string), typeof(InternalCreateBatchRequestEndpoint), typeof(InternalBatchCompletionTimeframe), typeof(IDictionary), typeof(CancellationToken))] [CodeGenSuppress("CreateBatch", typeof(BinaryContent), typeof(RequestOptions))] [CodeGenSuppress("CreateBatchAsync", typeof(BinaryContent), typeof(RequestOptions))] -[CodeGenSuppress("RetrieveBatch", typeof(string))] -[CodeGenSuppress("RetrieveBatchAsync", typeof(string))] -[CodeGenSuppress("CancelBatch", typeof(string))] -[CodeGenSuppress("CancelBatchAsync", typeof(string))] +[CodeGenSuppress("RetrieveBatch", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveBatchAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelBatch", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelBatchAsync", typeof(string), typeof(CancellationToken))] [CodeGenSuppress("CancelBatch", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CancelBatchAsync", typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetBatches", typeof(string), typeof(int?))] -[CodeGenSuppress("GetBatchesAsync", typeof(string), typeof(int?))] +[CodeGenSuppress("ListBatches", typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("ListBatchesAsync", typeof(string), typeof(int?), typeof(CancellationToken))] public partial class BatchClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public BatchClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -45,7 +40,7 @@ public partial class BatchClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public BatchClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -63,7 +58,7 @@ public BatchClient(ApiKeyCredential credential, OpenAIClientOptions options) Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -71,7 +66,7 @@ public BatchClient(ApiKeyCredential credential, OpenAIClientOptions options) // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -80,12 +75,12 @@ protected internal BatchClient(ClientPipeline pipeline, OpenAIClientOptions opti Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } internal virtual CreateBatchOperation CreateCreateBatchOperation(string batchId, string status, PipelineResponse response) { - return new CreateBatchOperation(_pipeline, _endpoint, batchId, status, response); + return new CreateBatchOperation(Pipeline, _endpoint, batchId, status, response); } } diff --git a/src/Custom/Chat/AssistantChatMessage.Serialization.cs b/src/Custom/Chat/AssistantChatMessage.Serialization.cs index 8fac611b9..d5fac5775 100644 --- a/src/Custom/Chat/AssistantChatMessage.Serialization.cs +++ b/src/Custom/Chat/AssistantChatMessage.Serialization.cs @@ -44,7 +44,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteOptionalProperty("name"u8, ParticipantName, options); writer.WriteOptionalCollection("tool_calls"u8, ToolCalls, options); writer.WriteOptionalProperty("function_call"u8, FunctionCall, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Chat/ChatClient.Protocol.cs b/src/Custom/Chat/ChatClient.Protocol.cs index 21a03c811..6e3264c35 100644 --- a/src/Custom/Chat/ChatClient.Protocol.cs +++ b/src/Custom/Chat/ChatClient.Protocol.cs @@ -25,7 +25,7 @@ public virtual async Task CompleteChatAsync(BinaryContent content, Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateChatCompletionRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -42,6 +42,6 @@ public virtual ClientResult CompleteChat(BinaryContent content, RequestOptions o Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateChatCompletionRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Chat/ChatClient.cs b/src/Custom/Chat/ChatClient.cs index b8c70d1cf..137200eb9 100644 --- a/src/Custom/Chat/ChatClient.cs +++ b/src/Custom/Chat/ChatClient.cs @@ -16,21 +16,15 @@ namespace OpenAI.Chat; /// The service client for OpenAI chat operations. [CodeGenClient("Chat")] [CodeGenSuppress("ChatClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateChatCompletionAsync", typeof(ChatCompletionOptions))] -[CodeGenSuppress("CreateChatCompletion", typeof(ChatCompletionOptions))] +[CodeGenSuppress("CreateChatCompletionAsync", typeof(ChatCompletionOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateChatCompletion", typeof(ChatCompletionOptions), typeof(CancellationToken))] public partial class ChatClient { private readonly string _model; private readonly OpenTelemetrySource _telemetry; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -43,7 +37,7 @@ public partial class ChatClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -57,7 +51,7 @@ public partial class ChatClient // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Added telemetry support. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -70,7 +64,7 @@ public ChatClient(string model, ApiKeyCredential credential, OpenAIClientOptions options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); _telemetry = new OpenTelemetrySource(model, _endpoint); } @@ -81,7 +75,7 @@ public ChatClient(string model, ApiKeyCredential credential, OpenAIClientOptions // - Demoted the endpoint parameter to be a property in the options class. // - Added telemetry support. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -94,7 +88,7 @@ protected internal ChatClient(ClientPipeline pipeline, string model, OpenAIClien options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); _telemetry = new OpenTelemetrySource(model, _endpoint); } @@ -115,10 +109,10 @@ public virtual async Task> CompleteChatAsync(IEnume try { - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await CompleteChatAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - ChatCompletion chatCompletion = ChatCompletion.FromResponse(result.GetRawResponse()); + ChatCompletion chatCompletion = (ChatCompletion)result; scope?.RecordChatCompletion(chatCompletion); return ClientResult.FromValue(chatCompletion, result.GetRawResponse()); } @@ -145,9 +139,9 @@ public virtual ClientResult CompleteChat(IEnumerable CompleteChat options ??= new(); CreateChatCompletionOptions(messages, ref options, stream: true); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; async Task sendRequestAsync() => await CompleteChatAsync(content, cancellationToken.ToRequestOptions(streaming: true)).ConfigureAwait(false); @@ -220,7 +214,7 @@ public virtual CollectionResult CompleteChatStrea options ??= new(); CreateChatCompletionOptions(messages, ref options, stream: true); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult sendRequest() => CompleteChat(content, cancellationToken.ToRequestOptions(streaming: true)); return new InternalStreamingChatCompletionUpdateCollection(sendRequest, cancellationToken); } diff --git a/src/Custom/Chat/ChatFunctionChoice.Serialization.cs b/src/Custom/Chat/ChatFunctionChoice.Serialization.cs index 0ad21b27b..d48adab0b 100644 --- a/src/Custom/Chat/ChatFunctionChoice.Serialization.cs +++ b/src/Custom/Chat/ChatFunctionChoice.Serialization.cs @@ -22,7 +22,7 @@ internal static void SerializeChatFunctionChoice(ChatFunctionChoice instance, Ut writer.WriteStartObject(); writer.WritePropertyName("name"u8); writer.WriteStringValue(instance._function.Name); - writer.WriteSerializedAdditionalRawData(instance.SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(instance._additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Chat/ChatFunctionChoice.cs b/src/Custom/Chat/ChatFunctionChoice.cs index df8f26393..248dfb662 100644 --- a/src/Custom/Chat/ChatFunctionChoice.cs +++ b/src/Custom/Chat/ChatFunctionChoice.cs @@ -43,7 +43,7 @@ internal ChatFunctionChoice(string functionName, IDictionary _function = new(functionName); _isPlainString = false; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; } /// diff --git a/src/Custom/Chat/ChatMessage.cs b/src/Custom/Chat/ChatMessage.cs index a88b3daba..78dcab46a 100644 --- a/src/Custom/Chat/ChatMessage.cs +++ b/src/Custom/Chat/ChatMessage.cs @@ -126,10 +126,10 @@ internal ChatMessage(ChatMessageRole role, string content = null) : this(role) /// public static AssistantChatMessage CreateAssistantMessage(params ChatMessageContentPart[] contentParts) => new(contentParts); - /// + /// public static AssistantChatMessage CreateAssistantMessage(IEnumerable toolCalls) => new(toolCalls); - /// + /// public static AssistantChatMessage CreateAssistantMessage(ChatFunctionCall functionCall) => new(functionCall); /// diff --git a/src/Custom/Chat/ChatMessageContentPart.Serialization.cs b/src/Custom/Chat/ChatMessageContentPart.Serialization.cs index 9a1916087..eb2277bf6 100644 --- a/src/Custom/Chat/ChatMessageContentPart.Serialization.cs +++ b/src/Custom/Chat/ChatMessageContentPart.Serialization.cs @@ -33,7 +33,7 @@ internal static void WriteCoreContentPart(ChatMessageContentPart instance, Utf8J writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(instance._imageUri, options); } - writer.WriteSerializedAdditionalRawData(instance.SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(instance._additionalBinaryDataProperties, options); writer.WriteEndObject(); } diff --git a/src/Custom/Chat/ChatMessageContentPart.cs b/src/Custom/Chat/ChatMessageContentPart.cs index 59f120815..f170d8b83 100644 --- a/src/Custom/Chat/ChatMessageContentPart.cs +++ b/src/Custom/Chat/ChatMessageContentPart.cs @@ -42,7 +42,7 @@ internal ChatMessageContentPart(ChatMessageContentPartKind kind, string text, In _text = text; _imageUri = imageUri; _refusal = refusal; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; } /// The kind of content part. diff --git a/src/Custom/Chat/ChatOutputTokenUsageDetails.cs b/src/Custom/Chat/ChatOutputTokenUsageDetails.cs index cb0316195..cf2be788d 100644 --- a/src/Custom/Chat/ChatOutputTokenUsageDetails.cs +++ b/src/Custom/Chat/ChatOutputTokenUsageDetails.cs @@ -5,7 +5,7 @@ namespace OpenAI.Chat; public partial class ChatOutputTokenUsageDetails { // CUSTOM: Renamed. - /// The number of tokens consumed internally by the model for the purpose of reasoning. + /// The number of tokens consumed internally by the model for the purpose of reasoning. /// Only applicable to models with reasoning capabilities, such as the OpenAI o1 series. [CodeGenMember("ReasoningTokens")] public int ReasoningTokenCount { get; } diff --git a/src/Custom/Chat/ChatResponseFormat.cs b/src/Custom/Chat/ChatResponseFormat.cs index 817ae5612..eb1f0f39d 100644 --- a/src/Custom/Chat/ChatResponseFormat.cs +++ b/src/Custom/Chat/ChatResponseFormat.cs @@ -97,9 +97,9 @@ public static ChatResponseFormat CreateJsonSchemaFormat(string jsonSchemaFormatN InternalResponseFormatJsonSchemaJsonSchema internalSchema = new( jsonSchemaFormatDescription, jsonSchemaFormatName, - jsonSchema, jsonSchemaIsStrict, - serializedAdditionalRawData: null); + schema: jsonSchema, + additionalBinaryDataProperties: null); return new InternalChatResponseFormatJsonSchema(internalSchema); } diff --git a/src/Custom/Chat/ChatTool.cs b/src/Custom/Chat/ChatTool.cs index 5811edc17..6cdb2f64b 100644 --- a/src/Custom/Chat/ChatTool.cs +++ b/src/Custom/Chat/ChatTool.cs @@ -59,7 +59,7 @@ internal ChatTool(InternalFunctionDefinition function) /// /// /// Whether to enable strict schema adherence when generating the function call. If set to true, the - /// model will follow the exact schema defined in + /// model will follow the exact schema defined in /// /// /// Only a subset of the JSON schema specification is supported when this is set to true. Learn more @@ -131,6 +131,6 @@ public static ChatTool CreateFunctionTool(string functionName, string functionDe return new( kind: ChatToolKind.Function, function: function, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } } diff --git a/src/Custom/Chat/ChatToolCall.cs b/src/Custom/Chat/ChatToolCall.cs index c0b2eb654..88df04d8c 100644 --- a/src/Custom/Chat/ChatToolCall.cs +++ b/src/Custom/Chat/ChatToolCall.cs @@ -6,7 +6,7 @@ namespace OpenAI.Chat; /// A tool call made by the model. /// /// -/// Call to create a +/// Call to create a /// representing a function call made by the model. /// /// @@ -60,6 +60,6 @@ public static ChatToolCall CreateFunctionToolCall(string id, string functionName id: id, kind: ChatToolCallKind.Function, function: function, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } } \ No newline at end of file diff --git a/src/Custom/Chat/ChatToolChoice.Serialization.cs b/src/Custom/Chat/ChatToolChoice.Serialization.cs index 964fc7566..283d52199 100644 --- a/src/Custom/Chat/ChatToolChoice.Serialization.cs +++ b/src/Custom/Chat/ChatToolChoice.Serialization.cs @@ -24,7 +24,7 @@ internal static void SerializeChatToolChoice(ChatToolChoice instance, Utf8JsonWr writer.WriteStringValue(instance._type.ToString()); writer.WritePropertyName("function"u8); writer.WriteObjectValue(instance._function, options); - writer.WriteSerializedAdditionalRawData(instance.SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(instance._additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Chat/ChatToolChoice.cs b/src/Custom/Chat/ChatToolChoice.cs index b82850a78..2c598de78 100644 --- a/src/Custom/Chat/ChatToolChoice.cs +++ b/src/Custom/Chat/ChatToolChoice.cs @@ -25,7 +25,6 @@ namespace OpenAI.Chat; /// /// [CodeGenModel("ChatCompletionToolChoice")] -[CodeGenSuppress("ChatToolChoice", typeof(IDictionary))] public partial class ChatToolChoice { private readonly bool _predefined; @@ -49,7 +48,7 @@ internal ChatToolChoice(bool predefined, string predefinedValue, InternalChatCom _predefinedValue = predefinedValue; _type = type; _function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; } /// diff --git a/src/Custom/Chat/FunctionChatMessage.Serialization.cs b/src/Custom/Chat/FunctionChatMessage.Serialization.cs index cf0404266..d3618bb1a 100644 --- a/src/Custom/Chat/FunctionChatMessage.Serialization.cs +++ b/src/Custom/Chat/FunctionChatMessage.Serialization.cs @@ -36,7 +36,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions } } - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } \ No newline at end of file diff --git a/src/Custom/Chat/FunctionChatMessage.cs b/src/Custom/Chat/FunctionChatMessage.cs index d2678a6af..f91e7730a 100644 --- a/src/Custom/Chat/FunctionChatMessage.cs +++ b/src/Custom/Chat/FunctionChatMessage.cs @@ -10,6 +10,7 @@ namespace OpenAI.Chat; /// [Obsolete($"This class is obsolete. Please use {nameof(ToolChatMessage)} instead.")] [CodeGenModel("ChatCompletionRequestFunctionMessage")] +[CodeGenSuppress("FunctionChatMessage", typeof(string))] [CodeGenSuppress("FunctionChatMessage", typeof(ChatMessageContent), typeof(string))] public partial class FunctionChatMessage : ChatMessage { diff --git a/src/Custom/Chat/Internal/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs b/src/Custom/Chat/Internal/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs index 5e308a3cc..ab2f56ab1 100644 --- a/src/Custom/Chat/Internal/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs +++ b/src/Custom/Chat/Internal/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs @@ -50,10 +50,10 @@ public InternalChatCompletionRequestMessageContentPartImageImageUrl(BinaryData i } /// Initializes a new instance of . - /// Either a URL of the image or the base64 encoded image data. /// Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + /// Either a URL of the image or the base64 encoded image data. /// Keeps track of any properties unknown to the library. - internal InternalChatCompletionRequestMessageContentPartImageImageUrl(string url, ChatImageDetailLevel? detail, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionRequestMessageContentPartImageImageUrl(ChatImageDetailLevel? detail, string url, IDictionary serializedAdditionalRawData) { Match parsedDataUri = ParseDataUriRegex().Match(url); @@ -69,7 +69,7 @@ internal InternalChatCompletionRequestMessageContentPartImageImageUrl(string url Url = url; Detail = detail; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; } public Uri ImageUri => _imageUri; diff --git a/src/Custom/Chat/Internal/InternalChatResponseFormatJsonObject.Serialization.cs b/src/Custom/Chat/Internal/InternalChatResponseFormatJsonObject.Serialization.cs index 586eaf06d..ffbb4950c 100644 --- a/src/Custom/Chat/Internal/InternalChatResponseFormatJsonObject.Serialization.cs +++ b/src/Custom/Chat/Internal/InternalChatResponseFormatJsonObject.Serialization.cs @@ -15,14 +15,14 @@ internal static void SerializeInternalChatResponseFormatJsonObject(InternalChatR internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { diff --git a/src/Custom/Chat/Internal/InternalChatResponseFormatJsonSchema.Serialization.cs b/src/Custom/Chat/Internal/InternalChatResponseFormatJsonSchema.Serialization.cs index e9b246f77..d6da14972 100644 --- a/src/Custom/Chat/Internal/InternalChatResponseFormatJsonSchema.Serialization.cs +++ b/src/Custom/Chat/Internal/InternalChatResponseFormatJsonSchema.Serialization.cs @@ -15,19 +15,19 @@ internal static void SerializeInternalChatResponseFormatJsonSchema(InternalChatR internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + if (_additionalBinaryDataProperties?.ContainsKey("json_schema") != true) { writer.WritePropertyName("json_schema"u8); writer.WriteObjectValue(JsonSchema, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { diff --git a/src/Custom/Chat/Internal/InternalChatResponseFormatText.Serialization.cs b/src/Custom/Chat/Internal/InternalChatResponseFormatText.Serialization.cs index 608844c67..54277f919 100644 --- a/src/Custom/Chat/Internal/InternalChatResponseFormatText.Serialization.cs +++ b/src/Custom/Chat/Internal/InternalChatResponseFormatText.Serialization.cs @@ -15,14 +15,14 @@ internal static void SerializeInternalChatResponseFormatText(InternalChatRespons internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { diff --git a/src/Custom/Chat/Internal/InternalUnknownChatMessage.Serialization.cs b/src/Custom/Chat/Internal/InternalUnknownChatMessage.Serialization.cs index 6379d9e4c..b753d8ef0 100644 --- a/src/Custom/Chat/Internal/InternalUnknownChatMessage.Serialization.cs +++ b/src/Custom/Chat/Internal/InternalUnknownChatMessage.Serialization.cs @@ -42,7 +42,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions } } - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Chat/Internal/InternalUnknownChatResponseFormat.Serialization.cs b/src/Custom/Chat/Internal/InternalUnknownChatResponseFormat.Serialization.cs index 0f7f3cec4..909c525df 100644 --- a/src/Custom/Chat/Internal/InternalUnknownChatResponseFormat.Serialization.cs +++ b/src/Custom/Chat/Internal/InternalUnknownChatResponseFormat.Serialization.cs @@ -15,14 +15,14 @@ internal static void SerializeChatResponseFormat(InternalUnknownChatResponseForm internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { diff --git a/src/Custom/Chat/OpenAIChatModelFactory.cs b/src/Custom/Chat/OpenAIChatModelFactory.cs index de93509a2..f4503f98e 100644 --- a/src/Custom/Chat/OpenAIChatModelFactory.cs +++ b/src/Custom/Chat/OpenAIChatModelFactory.cs @@ -30,17 +30,17 @@ public static ChatCompletion ChatCompletion( refusalTokenLogProbabilities ??= new List(); InternalChatCompletionResponseMessage message = new InternalChatCompletionResponseMessage( - content, refusal, toolCalls.ToList(), role, + content, functionCall, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); InternalCreateChatCompletionResponseChoiceLogprobs logprobs = new InternalCreateChatCompletionResponseChoiceLogprobs( contentTokenLogProbabilities.ToList(), refusalTokenLogProbabilities.ToList(), - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); IReadOnlyList choices = [ new InternalCreateChatCompletionResponseChoice( @@ -48,19 +48,19 @@ public static ChatCompletion ChatCompletion( index: 0, message, logprobs, - serializedAdditionalRawData: null) + additionalBinaryDataProperties: null) ]; return new ChatCompletion( id, - choices, - createdAt, model, - serviceTier: null, systemFingerprint, - InternalCreateChatCompletionResponseObject.ChatCompletion, usage, - serializedAdditionalRawData: null); + InternalCreateChatCompletionResponseObject.ChatCompletion, + serviceTier: null, + choices, + createdAt, + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -74,7 +74,7 @@ public static ChatTokenLogProbabilityDetails ChatTokenLogProbabilityDetails(stri logProbability, utf8Bytes, topLogProbabilities.ToList(), - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -85,7 +85,7 @@ public static ChatTokenTopLogProbabilityDetails ChatTokenTopLogProbabilityDetail token, logProbability, utf8Bytes, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -98,7 +98,7 @@ public static ChatTokenUsage ChatTokenUsage(int outputTokenCount = default, int totalTokenCount, outputTokenDetails, inputTokenDetails, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -108,17 +108,14 @@ public static ChatInputTokenUsageDetails ChatInputTokenUsageDetails(int audioTok return new ChatInputTokenUsageDetails( audioTokenCount: audioTokenCount, cachedTokenCount: cachedTokenCount, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . /// A new instance for mocking. public static ChatOutputTokenUsageDetails ChatOutputTokenUsageDetails(int reasoningTokenCount = default, int audioTokenCount = default) { - return new ChatOutputTokenUsageDetails( - audioTokenCount: audioTokenCount, - reasoningTokenCount: reasoningTokenCount, - serializedAdditionalRawData: null); + return new ChatOutputTokenUsageDetails(reasoningTokenCount, audioTokenCount, additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -144,37 +141,37 @@ public static StreamingChatCompletionUpdate StreamingChatCompletionUpdate( refusalTokenLogProbabilities ??= new List(); InternalChatCompletionStreamResponseDelta delta = new InternalChatCompletionStreamResponseDelta( - contentUpdate, functionCallUpdate, toolCallUpdates.ToList(), - role, refusalUpdate, - serializedAdditionalRawData: null); + role, + contentUpdate, + additionalBinaryDataProperties: null); InternalCreateChatCompletionStreamResponseChoiceLogprobs logprobs = new InternalCreateChatCompletionStreamResponseChoiceLogprobs( contentTokenLogProbabilities.ToList(), refusalTokenLogProbabilities.ToList(), - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); IReadOnlyList choices = [ new InternalCreateChatCompletionStreamResponseChoice( delta, logprobs, - finishReason, index: 0, - serializedAdditionalRawData: null) + finishReason, + additionalBinaryDataProperties: null) ]; return new StreamingChatCompletionUpdate( - completionId, - choices, - createdAt, model, - serviceTier: null, systemFingerprint, InternalCreateChatCompletionStreamResponseObject.ChatCompletionChunk, + completionId, + serviceTier: null, + choices, + createdAt, usage, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -183,9 +180,9 @@ public static StreamingChatCompletionUpdate StreamingChatCompletionUpdate( public static StreamingChatFunctionCallUpdate StreamingChatFunctionCallUpdate(string functionName = null, BinaryData functionArgumentsUpdate = null) { return new StreamingChatFunctionCallUpdate( - functionName: functionName, - functionArgumentsUpdate: functionArgumentsUpdate, - serializedAdditionalRawData: null); + functionName, + functionArgumentsUpdate, + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -195,13 +192,13 @@ public static StreamingChatToolCallUpdate StreamingChatToolCallUpdate(int index InternalChatCompletionMessageToolCallChunkFunction function = new InternalChatCompletionMessageToolCallChunkFunction( functionName, functionArgumentsUpdate, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); return new StreamingChatToolCallUpdate( index, - toolCallId, - kind, function, - serializedAdditionalRawData: null); + kind, + toolCallId, + additionalBinaryDataProperties: null); } } diff --git a/src/Custom/Chat/Streaming/InternalAsyncStreamingChatCompletionUpdateCollection.cs b/src/Custom/Chat/Streaming/InternalAsyncStreamingChatCompletionUpdateCollection.cs index ad391ccaf..847d8c89d 100644 --- a/src/Custom/Chat/Streaming/InternalAsyncStreamingChatCompletionUpdateCollection.cs +++ b/src/Custom/Chat/Streaming/InternalAsyncStreamingChatCompletionUpdateCollection.cs @@ -107,7 +107,7 @@ async ValueTask IAsyncEnumerator.MoveNextAs } using JsonDocument doc = JsonDocument.Parse(_events.Current.Data); - List updates = [StreamingChatCompletionUpdate.DeserializeStreamingChatCompletionUpdate(doc.RootElement)]; + List updates = [StreamingChatCompletionUpdate.DeserializeStreamingChatCompletionUpdate(doc.RootElement, ModelSerializationExtensions.WireOptions)]; _updates = updates.GetEnumerator(); if (_updates.MoveNext()) diff --git a/src/Custom/Chat/Streaming/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs b/src/Custom/Chat/Streaming/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs index 69b0c4c46..5d3b87e63 100644 --- a/src/Custom/Chat/Streaming/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs +++ b/src/Custom/Chat/Streaming/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs @@ -44,7 +44,7 @@ internal static void SerializeInternalCreateChatCompletionStreamResponseChoice(I } writer.WritePropertyName("index"u8); writer.WriteNumberValue(instance.Index); - writer.WriteSerializedAdditionalRawData(instance.SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(instance._additionalBinaryDataProperties, options); writer.WriteEndObject(); } @@ -100,6 +100,6 @@ internal static InternalCreateChatCompletionStreamResponseChoice DeserializeInte } } serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionStreamResponseChoice(delta, logprobs, finishReason, index, serializedAdditionalRawData); + return new InternalCreateChatCompletionStreamResponseChoice(delta, logprobs, index, finishReason, serializedAdditionalRawData); } } diff --git a/src/Custom/Chat/Streaming/InternalStreamingChatCompletionUpdateCollection.cs b/src/Custom/Chat/Streaming/InternalStreamingChatCompletionUpdateCollection.cs index e8ecb2648..dff069d7a 100644 --- a/src/Custom/Chat/Streaming/InternalStreamingChatCompletionUpdateCollection.cs +++ b/src/Custom/Chat/Streaming/InternalStreamingChatCompletionUpdateCollection.cs @@ -108,7 +108,7 @@ public bool MoveNext() } using JsonDocument doc = JsonDocument.Parse(_events.Current.Data); - List updates = [StreamingChatCompletionUpdate.DeserializeStreamingChatCompletionUpdate(doc.RootElement)]; + List updates = [StreamingChatCompletionUpdate.DeserializeStreamingChatCompletionUpdate(doc.RootElement, ModelSerializationExtensions.WireOptions)]; _updates = updates.GetEnumerator(); if (_updates.MoveNext()) diff --git a/src/Custom/Chat/Streaming/StreamingChatCompletionUpdate.cs b/src/Custom/Chat/Streaming/StreamingChatCompletionUpdate.cs index f89167c0d..54441795b 100644 --- a/src/Custom/Chat/Streaming/StreamingChatCompletionUpdate.cs +++ b/src/Custom/Chat/Streaming/StreamingChatCompletionUpdate.cs @@ -89,7 +89,7 @@ public partial class StreamingChatCompletionUpdate // CUSTOM: Flattened choice delta property. /// The contents of the message update. - /// + /// /// Each streaming update contains only a small portion of tokens. To reconstitute the entire chat completion, /// all values across streaming updates must be combined. /// diff --git a/src/Custom/Chat/Streaming/StreamingChatToolCallUpdate.cs b/src/Custom/Chat/Streaming/StreamingChatToolCallUpdate.cs index 639cbd57b..0256ac302 100644 --- a/src/Custom/Chat/Streaming/StreamingChatToolCallUpdate.cs +++ b/src/Custom/Chat/Streaming/StreamingChatToolCallUpdate.cs @@ -21,7 +21,7 @@ public partial class StreamingChatToolCallUpdate // CUSTOM: Renamed. /// /// The unique identifier of the tool call being streamed, as used with e.g. - /// or + /// or /// . /// [CodeGenMember("Id")] diff --git a/src/Custom/Chat/SystemChatMessage.Serialization.cs b/src/Custom/Chat/SystemChatMessage.Serialization.cs index b663776a5..4907c78bc 100644 --- a/src/Custom/Chat/SystemChatMessage.Serialization.cs +++ b/src/Custom/Chat/SystemChatMessage.Serialization.cs @@ -39,7 +39,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WriteOptionalProperty("name"u8, ParticipantName, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } \ No newline at end of file diff --git a/src/Custom/Chat/SystemChatMessage.cs b/src/Custom/Chat/SystemChatMessage.cs index b0a616c65..8e4cad09d 100644 --- a/src/Custom/Chat/SystemChatMessage.cs +++ b/src/Custom/Chat/SystemChatMessage.cs @@ -46,6 +46,11 @@ public SystemChatMessage(string content) Argument.AssertNotNull(content, nameof(content)); } + // CUSTOM: Hide the default constructor. + internal SystemChatMessage() + { + } + /// /// An optional name for the participant. /// diff --git a/src/Custom/Chat/ToolChatMessage.Serialization.cs b/src/Custom/Chat/ToolChatMessage.Serialization.cs index 45a9bb0c2..b3cc7e417 100644 --- a/src/Custom/Chat/ToolChatMessage.Serialization.cs +++ b/src/Custom/Chat/ToolChatMessage.Serialization.cs @@ -39,7 +39,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions } } - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } diff --git a/src/Custom/Chat/ToolChatMessage.cs b/src/Custom/Chat/ToolChatMessage.cs index 879f88617..16925d08c 100644 --- a/src/Custom/Chat/ToolChatMessage.cs +++ b/src/Custom/Chat/ToolChatMessage.cs @@ -21,6 +21,7 @@ namespace OpenAI.Chat; /// [CodeGenModel("ChatCompletionRequestToolMessage")] [CodeGenSuppress("ToolChatMessage", typeof(ChatMessageContent), typeof(string))] +[CodeGenSuppress("ToolChatMessage", typeof(string))] public partial class ToolChatMessage : ChatMessage { /// diff --git a/src/Custom/Chat/UserChatMessage.Serialization.cs b/src/Custom/Chat/UserChatMessage.Serialization.cs index 2528c6bda..615d62feb 100644 --- a/src/Custom/Chat/UserChatMessage.Serialization.cs +++ b/src/Custom/Chat/UserChatMessage.Serialization.cs @@ -38,7 +38,7 @@ internal override void WriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WriteOptionalProperty("name"u8, ParticipantName, options); - writer.WriteSerializedAdditionalRawData(SerializedAdditionalRawData, options); + writer.WriteSerializedAdditionalRawData(_additionalBinaryDataProperties, options); writer.WriteEndObject(); } } \ No newline at end of file diff --git a/src/Custom/Chat/UserChatMessage.cs b/src/Custom/Chat/UserChatMessage.cs index 302a4aff4..e2c97ca16 100644 --- a/src/Custom/Chat/UserChatMessage.cs +++ b/src/Custom/Chat/UserChatMessage.cs @@ -49,6 +49,11 @@ public UserChatMessage(string content) Argument.AssertNotNull(content, nameof(content)); } + // CUSTOM: Hide the default constructor. + internal UserChatMessage() + { + } + // CUSTOM: Rename. /// /// An optional name for the participant. diff --git a/src/Custom/Embeddings/EmbeddingClient.Protocol.cs b/src/Custom/Embeddings/EmbeddingClient.Protocol.cs index 94dfb9d6f..f908d51f3 100644 --- a/src/Custom/Embeddings/EmbeddingClient.Protocol.cs +++ b/src/Custom/Embeddings/EmbeddingClient.Protocol.cs @@ -28,7 +28,7 @@ public virtual async Task GenerateEmbeddingsAsync(BinaryContent co Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateEmbeddingRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -49,6 +49,6 @@ public virtual ClientResult GenerateEmbeddings(BinaryContent content, RequestOpt Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateEmbeddingRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } \ No newline at end of file diff --git a/src/Custom/Embeddings/EmbeddingClient.cs b/src/Custom/Embeddings/EmbeddingClient.cs index 3cbc9a09b..862f543b6 100644 --- a/src/Custom/Embeddings/EmbeddingClient.cs +++ b/src/Custom/Embeddings/EmbeddingClient.cs @@ -15,20 +15,14 @@ namespace OpenAI.Embeddings; /// The service client for OpenAI embedding operations. [CodeGenClient("Embeddings")] [CodeGenSuppress("EmbeddingClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateEmbeddingAsync", typeof(EmbeddingGenerationOptions))] -[CodeGenSuppress("CreateEmbedding", typeof(EmbeddingGenerationOptions))] +[CodeGenSuppress("CreateEmbeddingAsync", typeof(EmbeddingGenerationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateEmbedding", typeof(EmbeddingGenerationOptions), typeof(CancellationToken))] public partial class EmbeddingClient { private readonly string _model; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -41,7 +35,7 @@ public partial class EmbeddingClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -54,7 +48,7 @@ public partial class EmbeddingClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -67,7 +61,7 @@ public EmbeddingClient(string model, ApiKeyCredential credential, OpenAIClientOp options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -76,7 +70,7 @@ public EmbeddingClient(string model, ApiKeyCredential credential, OpenAIClientOp // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -89,7 +83,7 @@ protected internal EmbeddingClient(ClientPipeline pipeline, string model, OpenAI options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } @@ -107,9 +101,9 @@ public virtual async Task> GenerateEmbeddingAsync( options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(input), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((OpenAIEmbeddingCollection)result).FirstOrDefault(), result.GetRawResponse()); } // CUSTOM: Added to simplify generating a single embedding from a string input. @@ -126,9 +120,9 @@ public virtual ClientResult GenerateEmbedding(string input, Emb options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(input), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((OpenAIEmbeddingCollection)result).FirstOrDefault(), result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of strings instead of BinaryData. @@ -145,9 +139,9 @@ public virtual async Task> GenerateEmbed options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIEmbeddingCollection)result, result.GetRawResponse()); } @@ -165,9 +159,9 @@ public virtual ClientResult GenerateEmbeddings(IEnume options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIEmbeddingCollection)result, result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of ReadOnlyMemory tokens instead of BinaryData. @@ -184,9 +178,9 @@ public virtual async Task> GenerateEmbed options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIEmbeddingCollection)result, result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of ReadOnlyMemory of tokens instead of BinaryData. @@ -203,9 +197,9 @@ public virtual ClientResult GenerateEmbeddings(IEnume options ??= new(); CreateEmbeddingGenerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIEmbeddingCollection)result, result.GetRawResponse()); } private void CreateEmbeddingGenerationOptions(BinaryData input, ref EmbeddingGenerationOptions options) diff --git a/src/Custom/Embeddings/OpenAIEmbedding.cs b/src/Custom/Embeddings/OpenAIEmbedding.cs index 949a48f50..e27164e63 100644 --- a/src/Custom/Embeddings/OpenAIEmbedding.cs +++ b/src/Custom/Embeddings/OpenAIEmbedding.cs @@ -78,7 +78,7 @@ internal OpenAIEmbedding(int index, BinaryData embeddingProperty, InternalEmbedd Index = index; EmbeddingProperty = embeddingProperty; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = serializedAdditionalRawData; // Handle additional custom properties. _vector = ConvertToVectorOfFloats(embeddingProperty); diff --git a/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs b/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs index d6797d3a0..212807087 100644 --- a/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs +++ b/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs @@ -7,7 +7,8 @@ namespace OpenAI.Embeddings; [CodeGenModel("CreateEmbeddingResponse")] [CodeGenSuppress("Data")] [CodeGenSuppress(nameof(OpenAIEmbeddingCollection))] -[CodeGenSuppress(nameof(OpenAIEmbeddingCollection), typeof(IReadOnlyList), typeof(string), typeof(InternalCreateEmbeddingResponseObject), typeof(EmbeddingTokenUsage))] +[CodeGenSuppress(nameof(OpenAIEmbeddingCollection), typeof(string), typeof(EmbeddingTokenUsage))] +[CodeGenSuppress(nameof(OpenAIEmbeddingCollection), typeof(string), typeof(EmbeddingTokenUsage), typeof(InternalCreateEmbeddingResponseObject), typeof(IDictionary))] public partial class OpenAIEmbeddingCollection : ReadOnlyCollection { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. @@ -15,39 +16,6 @@ public partial class OpenAIEmbeddingCollection : ReadOnlyCollection - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - // CUSTOM: Set the inherited Items property via the base constructor in favor of the suppressed Data property. /// Initializes a new instance of . /// The list of embeddings generated by the model. diff --git a/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs b/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs index c4fd91322..1901ccfc5 100644 --- a/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs +++ b/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs @@ -38,6 +38,6 @@ public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokenCount = defa return new EmbeddingTokenUsage( inputTokenCount, totalTokenCount, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } } diff --git a/src/Custom/Files/Internal/InternalUploadsClient.cs b/src/Custom/Files/Internal/InternalUploadsClient.cs index 8150ce1bb..cc828239e 100644 --- a/src/Custom/Files/Internal/InternalUploadsClient.cs +++ b/src/Custom/Files/Internal/InternalUploadsClient.cs @@ -8,16 +8,11 @@ namespace OpenAI.Files; [CodeGenSuppress("InternalUploadsClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] internal partial class InternalUploadsClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. internal InternalUploadsClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -27,7 +22,7 @@ internal partial class InternalUploadsClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -36,7 +31,7 @@ internal InternalUploadsClient(ApiKeyCredential credential, OpenAIClientOptions Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -44,7 +39,7 @@ internal InternalUploadsClient(ApiKeyCredential credential, OpenAIClientOptions // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -53,7 +48,7 @@ protected internal InternalUploadsClient(ClientPipeline pipeline, OpenAIClientOp Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } } diff --git a/src/Custom/Files/OpenAIFileClient.Protocol.cs b/src/Custom/Files/OpenAIFileClient.Protocol.cs index 74395b6c1..a699ba158 100644 --- a/src/Custom/Files/OpenAIFileClient.Protocol.cs +++ b/src/Custom/Files/OpenAIFileClient.Protocol.cs @@ -9,8 +9,8 @@ namespace OpenAI.Files; [CodeGenSuppress("CreateFileAsync", typeof(BinaryContent), typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CreateFile", typeof(BinaryContent), typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetFilesAsync", typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetFiles", typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFilesAsync", typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFiles", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("RetrieveFileAsync", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("RetrieveFile", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("DeleteFileAsync", typeof(string), typeof(RequestOptions))] @@ -44,7 +44,7 @@ public virtual async Task UploadFileAsync(BinaryContent content, s Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateFileRequest(content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -72,7 +72,7 @@ public virtual ClientResult UploadFile(BinaryContent content, string contentType Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateFileRequest(content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -85,8 +85,8 @@ public virtual ClientResult UploadFile(BinaryContent content, string contentType [EditorBrowsable(EditorBrowsableState.Never)] public virtual async Task GetFilesAsync(string purpose, RequestOptions options) { - using PipelineMessage message = CreateGetFilesRequest(purpose, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + using PipelineMessage message = CreateListFilesRequest(purpose, options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -99,8 +99,8 @@ public virtual async Task GetFilesAsync(string purpose, RequestOpt [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetFiles(string purpose, RequestOptions options) { - using PipelineMessage message = CreateGetFilesRequest(purpose, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = CreateListFilesRequest(purpose, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -118,7 +118,7 @@ public virtual async Task GetFileAsync(string fileId, RequestOptio Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateRetrieveFileRequest(fileId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -136,7 +136,7 @@ public virtual ClientResult GetFile(string fileId, RequestOptions options) Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateRetrieveFileRequest(fileId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -154,7 +154,7 @@ public virtual async Task DeleteFileAsync(string fileId, RequestOp Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDeleteFileRequest(fileId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -172,7 +172,7 @@ public virtual ClientResult DeleteFile(string fileId, RequestOptions options) Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDeleteFileRequest(fileId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -190,7 +190,7 @@ public virtual async Task DownloadFileAsync(string fileId, Request Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDownloadFileRequest(fileId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -208,7 +208,7 @@ public virtual ClientResult DownloadFile(string fileId, RequestOptions options) Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDownloadFileRequest(fileId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -248,7 +248,7 @@ public virtual ClientResult CreateUpload(BinaryContent content, RequestOptions o /// The ID of the upload. /// The content to send as the body of the request. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. @@ -265,7 +265,7 @@ public virtual async Task AddUploadPartAsync(string uploadId, Bina /// The ID of the upload. /// The content to send as the body of the request. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. @@ -281,7 +281,7 @@ public virtual ClientResult AddUploadPart(string uploadId, BinaryContent content /// The ID of the upload. /// The content to send as the body of the request. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. @@ -297,7 +297,7 @@ public virtual async Task CompleteUploadAsync(string uploadId, Bin /// The ID of the upload. /// The content to send as the body of the request. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. @@ -312,7 +312,7 @@ public virtual ClientResult CompleteUpload(string uploadId, BinaryContent conten /// /// The ID of the upload. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. @@ -327,7 +327,7 @@ public virtual async Task CancelUploadAsync(string uploadId, Reque /// /// The ID of the upload. /// The request options, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. diff --git a/src/Custom/Files/OpenAIFileClient.cs b/src/Custom/Files/OpenAIFileClient.cs index aec05abea..2b50ac4d2 100644 --- a/src/Custom/Files/OpenAIFileClient.cs +++ b/src/Custom/Files/OpenAIFileClient.cs @@ -13,32 +13,18 @@ namespace OpenAI.Files; /// The service client for OpenAI file operations. [CodeGenClient("Files")] [CodeGenSuppress("OpenAIFileClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateFileAsync", typeof(InternalFileUploadOptions))] -[CodeGenSuppress("CreateFile", typeof(InternalFileUploadOptions))] -[CodeGenSuppress("GetFilesAsync", typeof(string))] -[CodeGenSuppress("GetFiles", typeof(string))] -[CodeGenSuppress("RetrieveFileAsync", typeof(string))] -[CodeGenSuppress("RetrieveFile", typeof(string))] -[CodeGenSuppress("DeleteFileAsync", typeof(string))] -[CodeGenSuppress("DeleteFile", typeof(string))] -[CodeGenSuppress("DownloadFileAsync", typeof(string))] -[CodeGenSuppress("DownloadFile", typeof(string))] +[CodeGenSuppress("ListFilesAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListFiles", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveFileAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveFile", typeof(string), typeof(CancellationToken))] public partial class OpenAIFileClient { private InternalUploadsClient _internalUploadsClient; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . - /// The name of the model to use in requests sent to the service. To learn more about the available models, see . + /// Initializes a new instance of . /// The API key to authenticate with the service. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. public OpenAIFileClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) { } @@ -46,7 +32,7 @@ public partial class OpenAIFileClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public OpenAIFileClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -56,7 +42,7 @@ public partial class OpenAIFileClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -65,16 +51,16 @@ public OpenAIFileClient(ApiKeyCredential credential, OpenAIClientOptions options Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); - _internalUploadsClient = new(_pipeline, options); + _internalUploadsClient = new(Pipeline, options); } // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -83,7 +69,7 @@ protected internal OpenAIFileClient(ClientPipeline pipeline, OpenAIClientOptions Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); _internalUploadsClient = new(pipeline, options); } @@ -112,7 +98,7 @@ public virtual async Task> UploadFileAsync(Stream file, using MultipartFormDataBinaryContent content = options.ToMultipartContent(file, filename); ClientResult result = await UploadFileAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFile)result, result.GetRawResponse()); } /// Uploads a file that can be used across various operations. @@ -139,7 +125,7 @@ public virtual ClientResult UploadFile(Stream file, string filename, using MultipartFormDataBinaryContent content = options.ToMultipartContent(file, filename); ClientResult result = UploadFile(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFile)result, result.GetRawResponse()); } /// Uploads a file that can be used across various operations. @@ -221,7 +207,7 @@ public virtual ClientResult UploadFile(string filePath, FileUploadPu public virtual async Task> GetFilesAsync(CancellationToken cancellationToken = default) { ClientResult result = await GetFilesAsync(null, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFileCollection)result, result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. @@ -229,7 +215,7 @@ public virtual async Task> GetFilesAsync(Canc public virtual ClientResult GetFiles(CancellationToken cancellationToken = default) { ClientResult result = GetFiles(null, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFileCollection)result, result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. @@ -238,7 +224,7 @@ public virtual ClientResult GetFiles(CancellationToken can public virtual async Task> GetFilesAsync(FilePurpose purpose, CancellationToken cancellationToken = default) { ClientResult result = await GetFilesAsync(purpose.ToSerialString(), cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFileCollection)result, result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. @@ -247,7 +233,7 @@ public virtual async Task> GetFilesAsync(File public virtual ClientResult GetFiles(FilePurpose purpose, CancellationToken cancellationToken = default) { ClientResult result = GetFiles(purpose.ToSerialString(), cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFileCollection)result, result.GetRawResponse()); } /// Gets basic information about the specified file. @@ -260,7 +246,7 @@ public virtual async Task> GetFileAsync(string fileId, Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = await GetFileAsync(fileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFile)result, result.GetRawResponse()); } /// Gets basic information about the specified file. @@ -273,7 +259,7 @@ public virtual ClientResult GetFile(string fileId, CancellationToken Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = GetFile(fileId, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIFile)result, result.GetRawResponse()); } /// Deletes the specified file. @@ -286,7 +272,7 @@ public virtual async Task> DeleteFileAsync(stri Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = await DeleteFileAsync(fileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(FileDeletionResult.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((FileDeletionResult)result, result.GetRawResponse()); } /// Deletes the specified file. @@ -299,7 +285,7 @@ public virtual ClientResult DeleteFile(string fileId, Cancel Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = DeleteFile(fileId, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(FileDeletionResult.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((FileDeletionResult)result, result.GetRawResponse()); } /// Downloads the content of the specified file. diff --git a/src/Custom/Files/OpenAIFileCollection.cs b/src/Custom/Files/OpenAIFileCollection.cs index d1591feb1..3114ff3b9 100644 --- a/src/Custom/Files/OpenAIFileCollection.cs +++ b/src/Custom/Files/OpenAIFileCollection.cs @@ -7,46 +7,13 @@ namespace OpenAI.Files; [CodeGenModel("ListFilesResponse")] [CodeGenSuppress("Data")] [CodeGenSuppress(nameof(OpenAIFileCollection))] -[CodeGenSuppress(nameof(OpenAIFileCollection), typeof(IReadOnlyList), typeof(InternalListFilesResponseObject))] +[CodeGenSuppress(nameof(OpenAIFileCollection),typeof(InternalListFilesResponseObject), typeof(IDictionary))] public partial class OpenAIFileCollection : ReadOnlyCollection { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// Gets the object. private InternalListFilesResponseObject Object { get; } = InternalListFilesResponseObject.List; - - // CUSTOM: Recovered this field. See https://github.com/Azure/autorest.csharp/issues/4636. - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - + /// Initializes a new instance of . /// /// is null. diff --git a/src/Custom/Files/OpenAIFilesModelFactory.cs b/src/Custom/Files/OpenAIFilesModelFactory.cs index 115fdcca9..3dcaafacc 100644 --- a/src/Custom/Files/OpenAIFilesModelFactory.cs +++ b/src/Custom/Files/OpenAIFilesModelFactory.cs @@ -12,10 +12,10 @@ public static partial class OpenAIFilesModelFactory public static FileDeletionResult FileDeletionResult(string fileId = null, bool deleted = default) { return new FileDeletionResult( + deleted, fileId, InternalDeleteFileResponseObject.File, - deleted, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -24,14 +24,14 @@ public static OpenAIFile OpenAIFileInfo(string id = null, int? sizeInBytes = nul { return new OpenAIFile( id, - sizeInBytes, createdAt, filename, - @object: InternalOpenAIFileObject.File, purpose, + @object: InternalOpenAIFileObject.File, + sizeInBytes, status, statusDetails, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . diff --git a/src/Custom/FineTuning/FineTuningClient.Protocol.cs b/src/Custom/FineTuning/FineTuningClient.Protocol.cs index fe8f8a6bd..1f3c25c5d 100644 --- a/src/Custom/FineTuning/FineTuningClient.Protocol.cs +++ b/src/Custom/FineTuning/FineTuningClient.Protocol.cs @@ -8,16 +8,16 @@ namespace OpenAI.FineTuning; [CodeGenSuppress("CreateFineTuningJobAsync", typeof(BinaryContent), typeof(RequestOptions))] [CodeGenSuppress("CreateFineTuningJob", typeof(BinaryContent), typeof(RequestOptions))] -[CodeGenSuppress("GetPaginatedFineTuningJobsAsync", typeof(string), typeof(int?), typeof(RequestOptions))] -[CodeGenSuppress("GetPaginatedFineTuningJobs", typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListPaginatedFineTuningJobsAsync", typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListPaginatedFineTuningJobs", typeof(string), typeof(int?), typeof(RequestOptions))] [CodeGenSuppress("RetrieveFineTuningJobAsync", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("RetrieveFineTuningJob", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CancelFineTuningJobAsync", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CancelFineTuningJob", typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetFineTuningEventsAsync", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] -[CodeGenSuppress("GetFineTuningEvents", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] -[CodeGenSuppress("GetFineTuningJobCheckpointsAsync", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] -[CodeGenSuppress("GetFineTuningJobCheckpoints", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListFineTuningEventsAsync", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListFineTuningEvents", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListFineTuningJobCheckpointsAsync", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] +[CodeGenSuppress("ListFineTuningJobCheckpoints", typeof(string), typeof(string), typeof(int?), typeof(RequestOptions))] public partial class FineTuningClient { // CUSTOM: @@ -49,7 +49,7 @@ public virtual async Task CreateFineTuningJobAsync( Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateFineTuningJobRequest(content, options); - PipelineResponse response = await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); + PipelineResponse response = await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); using JsonDocument doc = JsonDocument.Parse(response.Content); string jobId = doc.RootElement.GetProperty("id"u8).GetString(); @@ -88,7 +88,7 @@ public virtual FineTuningJobOperation CreateFineTuningJob( Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateFineTuningJobRequest(content, options); - PipelineResponse response = _pipeline.ProcessMessage(message, options); + PipelineResponse response = Pipeline.ProcessMessage(message, options); using JsonDocument doc = JsonDocument.Parse(response.Content); string jobId = doc.RootElement.GetProperty("id"u8).GetString(); @@ -111,7 +111,7 @@ public virtual FineTuningJobOperation CreateFineTuningJob( /// The response returned from the service. public virtual AsyncCollectionResult GetJobsAsync(string after, int? limit, RequestOptions options) { - return new AsyncFineTuningJobCollectionResult(this, _pipeline, options, limit, after); + return new AsyncFineTuningJobCollectionResult(this, Pipeline, options, limit, after); } // CUSTOM: @@ -127,7 +127,7 @@ public virtual AsyncCollectionResult GetJobsAsync(string after, int? limit, Requ /// The response returned from the service. public virtual CollectionResult GetJobs(string after, int? limit, RequestOptions options) { - return new FineTuningJobCollectionResult(this, _pipeline, options, limit, after); + return new FineTuningJobCollectionResult(this, Pipeline, options, limit, after); } // CUSTOM: @@ -149,7 +149,7 @@ public virtual async Task GetJobAsync(string fineTuningJobId, Requ Argument.AssertNotNullOrEmpty(fineTuningJobId, nameof(fineTuningJobId)); using PipelineMessage message = CreateRetrieveFineTuningJobRequest(fineTuningJobId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -171,12 +171,12 @@ public virtual ClientResult GetJob(string fineTuningJobId, RequestOptions option Argument.AssertNotNullOrEmpty(fineTuningJobId, nameof(fineTuningJobId)); using PipelineMessage message = CreateRetrieveFineTuningJobRequest(fineTuningJobId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } internal virtual PipelineMessage CreateCreateFineTuningJobRequest(BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -193,7 +193,7 @@ internal virtual PipelineMessage CreateCreateFineTuningJobRequest(BinaryContent internal virtual PipelineMessage CreateGetPaginatedFineTuningJobsRequest(string after, int? limit, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -216,7 +216,7 @@ internal virtual PipelineMessage CreateGetPaginatedFineTuningJobsRequest(string internal virtual PipelineMessage CreateRetrieveFineTuningJobRequest(string fineTuningJobId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; diff --git a/src/Custom/FineTuning/FineTuningClient.cs b/src/Custom/FineTuning/FineTuningClient.cs index aaf581b50..5c9d78c15 100644 --- a/src/Custom/FineTuning/FineTuningClient.cs +++ b/src/Custom/FineTuning/FineTuningClient.cs @@ -2,6 +2,7 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Diagnostics.CodeAnalysis; +using System.Threading; namespace OpenAI.FineTuning; @@ -13,28 +14,22 @@ namespace OpenAI.FineTuning; [Experimental("OPENAI001")] [CodeGenClient("FineTuning")] [CodeGenSuppress("FineTuningClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateFineTuningJobAsync", typeof(FineTuningOptions))] -[CodeGenSuppress("CreateFineTuningJob", typeof(FineTuningOptions))] -[CodeGenSuppress("GetPaginatedFineTuningJobsAsync", typeof(string), typeof(int?))] -[CodeGenSuppress("GetPaginatedFineTuningJobs", typeof(string), typeof(int?))] -[CodeGenSuppress("RetrieveFineTuningJobAsync", typeof(string))] -[CodeGenSuppress("RetrieveFineTuningJob", typeof(string))] -[CodeGenSuppress("CancelFineTuningJobAsync", typeof(string))] -[CodeGenSuppress("CancelFineTuningJob", typeof(string))] -[CodeGenSuppress("GetFineTuningEventsAsync", typeof(string), typeof(string), typeof(int?))] -[CodeGenSuppress("GetFineTuningEvents", typeof(string), typeof(string), typeof(int?))] -[CodeGenSuppress("GetFineTuningJobCheckpointsAsync", typeof(string), typeof(string), typeof(int?))] -[CodeGenSuppress("GetFineTuningJobCheckpoints", typeof(string), typeof(string), typeof(int?))] +[CodeGenSuppress("CreateFineTuningJobAsync", typeof(FineTuningOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateFineTuningJob", typeof(FineTuningOptions), typeof(CancellationToken))] +[CodeGenSuppress("ListPaginatedFineTuningJobsAsync", typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("ListPaginatedFineTuningJobs", typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveFineTuningJobAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveFineTuningJob", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelFineTuningJobAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelFineTuningJob", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListFineTuningEventsAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("ListFineTuningEvents", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("ListFineTuningJobCheckpointsAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] +[CodeGenSuppress("ListFineTuningJobCheckpoints", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] public partial class FineTuningClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public FineTuningClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -44,7 +39,7 @@ public partial class FineTuningClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public FineTuningClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -62,7 +57,7 @@ public FineTuningClient(ApiKeyCredential credential, OpenAIClientOptions options Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -70,7 +65,7 @@ public FineTuningClient(ApiKeyCredential credential, OpenAIClientOptions options // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -79,12 +74,12 @@ protected internal FineTuningClient(ClientPipeline pipeline, OpenAIClientOptions Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } internal virtual FineTuningJobOperation CreateCreateJobOperation(string jobId, string status, PipelineResponse response) { - return new FineTuningJobOperation(_pipeline, _endpoint, jobId, status, response); + return new FineTuningJobOperation(Pipeline, _endpoint, jobId, status, response); } } diff --git a/src/Custom/FineTuning/Internal/GeneratorStubs.cs b/src/Custom/FineTuning/Internal/GeneratorStubs.cs index 3f15419f9..eb14cf3bd 100644 --- a/src/Custom/FineTuning/Internal/GeneratorStubs.cs +++ b/src/Custom/FineTuning/Internal/GeneratorStubs.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.InteropServices; namespace OpenAI.FineTuning; @@ -107,9 +108,9 @@ internal enum FineTuningJobEventLevel } [CodeGenModel("FineTuningJobHyperparameters")] +[StructLayout(LayoutKind.Auto)] internal readonly partial struct FineTuningJobHyperparameters { - internal readonly IDictionary SerializedAdditionalRawData { get; } public BinaryData NEpochs { get; } public BinaryData BatchSize { get; } public BinaryData LearningRateMultiplier { get; } diff --git a/src/Custom/Images/GeneratedImageCollection.cs b/src/Custom/Images/GeneratedImageCollection.cs index 0b49f793e..4679345ae 100644 --- a/src/Custom/Images/GeneratedImageCollection.cs +++ b/src/Custom/Images/GeneratedImageCollection.cs @@ -11,42 +11,10 @@ namespace OpenAI.Images; [CodeGenSuppress("Data")] [CodeGenSuppress("Created")] [CodeGenSuppress(nameof(GeneratedImageCollection))] -[CodeGenSuppress(nameof(GeneratedImageCollection), typeof(DateTimeOffset), typeof(IReadOnlyList))] +[CodeGenSuppress(nameof(GeneratedImageCollection), typeof(DateTimeOffset))] +[CodeGenSuppress(nameof(GeneratedImageCollection), typeof(DateTimeOffset), typeof(IDictionary))] public partial class GeneratedImageCollection : ReadOnlyCollection { - // CUSTOM: Recovered this field. See https://github.com/Azure/autorest.csharp/issues/4636. - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - // CUSTOM: Set the inherited Items property via the base constructor in favor of the suppressed Data property. /// Initializes a new instance of . /// diff --git a/src/Custom/Images/GeneratedImageFormat.cs b/src/Custom/Images/GeneratedImageFormat.cs index 79984385b..499354405 100644 --- a/src/Custom/Images/GeneratedImageFormat.cs +++ b/src/Custom/Images/GeneratedImageFormat.cs @@ -8,7 +8,7 @@ public readonly partial struct GeneratedImageFormat // CUSTOM: Renamed. /// Returned as bytes in a base64-encoded string. [CodeGenMember("B64Json")] - public static GeneratedImageFormat Bytes { get; } = new GeneratedImageFormat(BytesValue); + public static GeneratedImageFormat Bytes { get; } = new GeneratedImageFormat(B64JsonValue); // CUSTOM: Renamed. /// @@ -16,5 +16,5 @@ public readonly partial struct GeneratedImageFormat /// only valid for 60 minutes after the image is generated. /// [CodeGenMember("Url")] - public static GeneratedImageFormat Uri { get; } = new GeneratedImageFormat(UriValue); + public static GeneratedImageFormat Uri { get; } = new GeneratedImageFormat(UrlValue); } \ No newline at end of file diff --git a/src/Custom/Images/GeneratedImageQuality.cs b/src/Custom/Images/GeneratedImageQuality.cs index df4a59e08..b769e599b 100644 --- a/src/Custom/Images/GeneratedImageQuality.cs +++ b/src/Custom/Images/GeneratedImageQuality.cs @@ -9,5 +9,5 @@ namespace OpenAI.Images; public readonly partial struct GeneratedImageQuality { [CodeGenMember("Hd")] - public static GeneratedImageQuality High { get; } = new GeneratedImageQuality(HighValue); + public static GeneratedImageQuality High { get; } = new GeneratedImageQuality(HdValue); } \ No newline at end of file diff --git a/src/Custom/Images/GeneratedImageSize.cs b/src/Custom/Images/GeneratedImageSize.cs index 8b16ccc39..f2a9050f6 100644 --- a/src/Custom/Images/GeneratedImageSize.cs +++ b/src/Custom/Images/GeneratedImageSize.cs @@ -6,11 +6,10 @@ namespace OpenAI.Images; /// The size of the image that will be generated. [CodeGenModel("CreateImageRequestSize")] [CodeGenSuppress("GeneratedImageSize", typeof(string))] -[CodeGenSuppress("op_Implicit", typeof(string))] +// CUSTOM: remove the implicit operator +[CodeGenSuppress("", typeof(string))] public readonly partial struct GeneratedImageSize : IEquatable { - private readonly string _value; - /// Initializes a new instance of . /// is null. internal GeneratedImageSize(string value) diff --git a/src/Custom/Images/ImageClient.Protocol.cs b/src/Custom/Images/ImageClient.Protocol.cs index b0ffff651..8cadc9996 100644 --- a/src/Custom/Images/ImageClient.Protocol.cs +++ b/src/Custom/Images/ImageClient.Protocol.cs @@ -32,7 +32,7 @@ public virtual async Task GenerateImagesAsync(BinaryContent conten Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateImageRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -53,7 +53,7 @@ public virtual ClientResult GenerateImages(BinaryContent content, RequestOptions Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateImageRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } // CUSTOM: @@ -79,7 +79,7 @@ public virtual async Task GenerateImageEditsAsync(BinaryContent co Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateImageEditRequest(content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -105,7 +105,7 @@ public virtual ClientResult GenerateImageEdits(BinaryContent content, string con Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateImageEditRequest(content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } // CUSTOM: @@ -131,7 +131,7 @@ public virtual async Task GenerateImageVariationsAsync(BinaryConte Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateImageVariationRequest(content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } // CUSTOM: @@ -157,6 +157,6 @@ public virtual ClientResult GenerateImageVariations(BinaryContent content, strin Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); using PipelineMessage message = CreateCreateImageVariationRequest(content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Images/ImageClient.cs b/src/Custom/Images/ImageClient.cs index 297f89512..7eda78f4f 100644 --- a/src/Custom/Images/ImageClient.cs +++ b/src/Custom/Images/ImageClient.cs @@ -15,24 +15,14 @@ namespace OpenAI.Images; /// The service client for OpenAI image operations. [CodeGenClient("Images")] [CodeGenSuppress("ImageClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateImageAsync", typeof(ImageGenerationOptions))] -[CodeGenSuppress("CreateImage", typeof(ImageGenerationOptions))] -[CodeGenSuppress("CreateImageEditAsync", typeof(ImageEditOptions))] -[CodeGenSuppress("CreateImageEdit", typeof(ImageEditOptions))] -[CodeGenSuppress("CreateImageVariationAsync", typeof(ImageVariationOptions))] -[CodeGenSuppress("CreateImageVariation", typeof(ImageVariationOptions))] +[CodeGenSuppress("CreateImageAsync", typeof(ImageGenerationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateImage", typeof(ImageGenerationOptions), typeof(CancellationToken))] public partial class ImageClient { private readonly string _model; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -45,7 +35,7 @@ public partial class ImageClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -58,7 +48,7 @@ public partial class ImageClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -71,7 +61,7 @@ public ImageClient(string model, ApiKeyCredential credential, OpenAIClientOption options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -80,7 +70,7 @@ public ImageClient(string model, ApiKeyCredential credential, OpenAIClientOption // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -93,7 +83,7 @@ protected internal ImageClient(ClientPipeline pipeline, string model, OpenAIClie options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } @@ -112,9 +102,9 @@ public virtual async Task> GenerateImageAsync(strin options ??= new(); CreateImageGenerationOptions(prompt, null, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateImagesAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates an image based on a prompt. @@ -130,9 +120,9 @@ public virtual ClientResult GenerateImage(string prompt, ImageGe options ??= new(); CreateImageGenerationOptions(prompt, null, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateImages(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates images based on a prompt. @@ -149,9 +139,9 @@ public virtual async Task> GenerateImages options ??= new(); CreateImageGenerationOptions(prompt, imageCount, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await GenerateImagesAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates images based on a prompt. @@ -168,9 +158,9 @@ public virtual ClientResult GenerateImages(string prom options ??= new(); CreateImageGenerationOptions(prompt, imageCount, ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = GenerateImages(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } #endregion @@ -203,7 +193,7 @@ public virtual async Task> GenerateImageEditAsync(S using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, null, null); ClientResult result = await GenerateImageEditsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates an edited or extended image based on an original image and a prompt. @@ -232,7 +222,7 @@ public virtual ClientResult GenerateImageEdit(Stream image, stri using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, null, null); ClientResult result = GenerateImageEdits(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates an edited or extended image based on an original image and a prompt. @@ -309,7 +299,7 @@ public virtual async Task> GenerateImageEditAsync(S using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, mask, maskFilename); ClientResult result = await GenerateImageEditsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates an edited or extended image based on an original image, a prompt, and a mask. @@ -346,7 +336,7 @@ public virtual ClientResult GenerateImageEdit(Stream image, stri using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, mask, maskFilename); ClientResult result = GenerateImageEdits(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates an edited or extended image based on an original image, a prompt, and a mask. @@ -432,7 +422,7 @@ public virtual async Task> GenerateImageE using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, null, null); ClientResult result = await GenerateImageEditsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates edited or extended images based on an original image and a prompt. @@ -462,7 +452,7 @@ public virtual ClientResult GenerateImageEdits(Stream using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, null, null); ClientResult result = GenerateImageEdits(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates edited or extended images based on an original image and a prompt. @@ -542,7 +532,7 @@ public virtual async Task> GenerateImageE using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, mask, maskFilename); ClientResult result = await GenerateImageEditsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates edited or extended images based on an original image, a prompt, and a mask. @@ -580,7 +570,7 @@ public virtual ClientResult GenerateImageEdits(Stream using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename, mask, maskFilename); ClientResult result = GenerateImageEdits(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates edited or extended images based on an original image, a prompt, and a mask. @@ -666,7 +656,7 @@ public virtual async Task> GenerateImageVariationAs using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename); ClientResult result = await GenerateImageVariationsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates a variation of a given image. @@ -690,7 +680,7 @@ public virtual ClientResult GenerateImageVariation(Stream image, using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename); ClientResult result = GenerateImageVariations(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((GeneratedImageCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Generates a variation of a given image. @@ -751,7 +741,7 @@ public virtual async Task> GenerateImageV using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename); ClientResult result = await GenerateImageVariationsAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates variations of a given image. @@ -776,7 +766,7 @@ public virtual ClientResult GenerateImageVariations(St using MultipartFormDataBinaryContent content = options.ToMultipartContent(image, imageFilename); ClientResult result = GenerateImageVariations(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(GeneratedImageCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((GeneratedImageCollection)result, result.GetRawResponse()); } /// Generates variations of a given image. diff --git a/src/Custom/Images/OpenAIImagesModelFactory.cs b/src/Custom/Images/OpenAIImagesModelFactory.cs index c318ff416..c84781c50 100644 --- a/src/Custom/Images/OpenAIImagesModelFactory.cs +++ b/src/Custom/Images/OpenAIImagesModelFactory.cs @@ -12,10 +12,10 @@ public static partial class OpenAIImagesModelFactory public static GeneratedImage GeneratedImage(BinaryData imageBytes = null, Uri imageUri = null, string revisedPrompt = null) { return new GeneratedImage( + revisedPrompt, imageBytes, imageUri, - revisedPrompt, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . diff --git a/src/Custom/Internal/InternalFunctionDefinition.cs b/src/Custom/Internal/InternalFunctionDefinition.cs index 0909a1c32..7c4dafb6c 100644 --- a/src/Custom/Internal/InternalFunctionDefinition.cs +++ b/src/Custom/Internal/InternalFunctionDefinition.cs @@ -9,5 +9,5 @@ internal partial class InternalFunctionDefinition /// The parameters to the function, formatting as a JSON Schema object. /// [CodeGenMember("Parameters")] - internal BinaryData Parameters; + internal BinaryData Parameters { get; set; } } diff --git a/src/Custom/LegacyCompletions/Internal/LegacyCompletionClient.cs b/src/Custom/LegacyCompletions/Internal/LegacyCompletionClient.cs index 09b149c4d..11491662e 100644 --- a/src/Custom/LegacyCompletions/Internal/LegacyCompletionClient.cs +++ b/src/Custom/LegacyCompletions/Internal/LegacyCompletionClient.cs @@ -15,14 +15,8 @@ internal partial class LegacyCompletionClient { private readonly string _model; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -35,7 +29,7 @@ internal partial class LegacyCompletionClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -48,7 +42,7 @@ internal partial class LegacyCompletionClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -61,7 +55,7 @@ public LegacyCompletionClient(string model, ApiKeyCredential credential, OpenAIC options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -70,7 +64,7 @@ public LegacyCompletionClient(string model, ApiKeyCredential credential, OpenAIC // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -83,7 +77,7 @@ protected internal LegacyCompletionClient(ClientPipeline pipeline, string model, options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } } diff --git a/src/Custom/Models/OpenAIModelClient.Protocol.cs b/src/Custom/Models/OpenAIModelClient.Protocol.cs index 8c5198774..476db90e3 100644 --- a/src/Custom/Models/OpenAIModelClient.Protocol.cs +++ b/src/Custom/Models/OpenAIModelClient.Protocol.cs @@ -6,8 +6,8 @@ namespace OpenAI.Models; -[CodeGenSuppress("GetModelsAsync", typeof(RequestOptions))] -[CodeGenSuppress("GetModels", typeof(RequestOptions))] +[CodeGenSuppress("ListModelsAsync", typeof(RequestOptions))] +[CodeGenSuppress("ListModels", typeof(RequestOptions))] [CodeGenSuppress("RetrieveModelAsync", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("RetrieveModel", typeof(string), typeof(RequestOptions))] [CodeGenSuppress("DeleteModelAsync", typeof(string), typeof(RequestOptions))] @@ -24,8 +24,8 @@ public partial class OpenAIModelClient [EditorBrowsable(EditorBrowsableState.Never)] public virtual async Task GetModelsAsync(RequestOptions options) { - using PipelineMessage message = CreateGetModelsRequest(options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + using PipelineMessage message = CreateListModelsRequest(options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -38,8 +38,8 @@ public virtual async Task GetModelsAsync(RequestOptions options) [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetModels(RequestOptions options) { - using PipelineMessage message = CreateGetModelsRequest(options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = CreateListModelsRequest(options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -58,7 +58,7 @@ public virtual async Task GetModelAsync(string model, RequestOptio Argument.AssertNotNullOrEmpty(model, nameof(model)); using PipelineMessage message = CreateRetrieveModelRequest(model, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -77,7 +77,7 @@ public virtual ClientResult GetModel(string model, RequestOptions options) Argument.AssertNotNullOrEmpty(model, nameof(model)); using PipelineMessage message = CreateRetrieveModelRequest(model, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -95,7 +95,7 @@ public virtual async Task DeleteModelAsync(string model, RequestOp Argument.AssertNotNullOrEmpty(model, nameof(model)); using PipelineMessage message = CreateDeleteModelRequest(model, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -113,6 +113,6 @@ public virtual ClientResult DeleteModel(string model, RequestOptions options) Argument.AssertNotNullOrEmpty(model, nameof(model)); using PipelineMessage message = CreateDeleteModelRequest(model, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Models/OpenAIModelClient.cs b/src/Custom/Models/OpenAIModelClient.cs index 96269e6d3..9cce4d38e 100644 --- a/src/Custom/Models/OpenAIModelClient.cs +++ b/src/Custom/Models/OpenAIModelClient.cs @@ -13,23 +13,15 @@ namespace OpenAI.Models; /// The service client for OpenAI model operations. [CodeGenClient("ModelsOps")] [CodeGenSuppress("OpenAIModelClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("GetModelsAsync")] -[CodeGenSuppress("GetModels")] -[CodeGenSuppress("RetrieveModelAsync", typeof(string))] -[CodeGenSuppress("RetrieveModel", typeof(string))] -[CodeGenSuppress("DeleteModelAsync", typeof(string))] -[CodeGenSuppress("DeleteModel", typeof(string))] +[CodeGenSuppress("ListModelsAsync", typeof(CancellationToken))] +[CodeGenSuppress("ListModels", typeof(CancellationToken))] +[CodeGenSuppress("RetrieveModelAsync", typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("RetrieveModel", typeof(string), typeof(CancellationToken))] public partial class OpenAIModelClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public OpenAIModelClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -39,7 +31,7 @@ public partial class OpenAIModelClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public OpenAIModelClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -49,7 +41,7 @@ public partial class OpenAIModelClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -58,7 +50,7 @@ public OpenAIModelClient(ApiKeyCredential credential, OpenAIClientOptions option Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -66,7 +58,7 @@ public OpenAIModelClient(ApiKeyCredential credential, OpenAIClientOptions option // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -75,7 +67,7 @@ protected internal OpenAIModelClient(ClientPipeline pipeline, OpenAIClientOption Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } @@ -84,7 +76,7 @@ protected internal OpenAIModelClient(ClientPipeline pipeline, OpenAIClientOption public virtual async Task> GetModelsAsync(CancellationToken cancellationToken = default) { ClientResult result = await GetModelsAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIModelCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIModelCollection)result, result.GetRawResponse()); } /// Gets basic information about each of the models that are currently available, such as their corresponding owner and availability. @@ -92,7 +84,7 @@ public virtual async Task> GetModelsAsync(Ca public virtual ClientResult GetModels(CancellationToken cancellationToken = default) { ClientResult result = GetModels(cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIModelCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIModelCollection)result, result.GetRawResponse()); } /// Gets basic information about the specified model, such as its owner and availability. @@ -105,7 +97,7 @@ public virtual async Task> GetModelAsync(string model, Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = await GetModelAsync(model, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIModel.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIModel)result, result.GetRawResponse()); } /// Gets basic information about the specified model, such as its owner and availability. @@ -118,7 +110,7 @@ public virtual ClientResult GetModel(string model, CancellationToke Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = GetModel(model, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIModel.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((OpenAIModel)result, result.GetRawResponse()); } /// Deletes the specified fine-tuned model. @@ -132,7 +124,7 @@ public virtual async Task> DeleteModelAsync(st Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = await DeleteModelAsync(model, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(ModelDeletionResult.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((ModelDeletionResult)result, result.GetRawResponse()); } /// Deletes the specified fine-tuned model. @@ -146,6 +138,6 @@ public virtual ClientResult DeleteModel(string model, Cance Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = DeleteModel(model, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(ModelDeletionResult.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((ModelDeletionResult)result, result.GetRawResponse()); } } diff --git a/src/Custom/Models/OpenAIModelCollection.cs b/src/Custom/Models/OpenAIModelCollection.cs index c850dc079..a3f179dc4 100644 --- a/src/Custom/Models/OpenAIModelCollection.cs +++ b/src/Custom/Models/OpenAIModelCollection.cs @@ -11,46 +11,13 @@ namespace OpenAI.Models; [CodeGenModel("ListModelsResponse")] [CodeGenSuppress("Data")] [CodeGenSuppress(nameof(OpenAIModelCollection))] -[CodeGenSuppress(nameof(OpenAIModelCollection), typeof(InternalListModelsResponseObject), typeof(IReadOnlyList))] +[CodeGenSuppress(nameof(OpenAIModelCollection), typeof(InternalListModelsResponseObject), typeof(IDictionary))] public partial class OpenAIModelCollection : ReadOnlyCollection { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// Gets the object. private InternalListModelsResponseObject Object { get; } = InternalListModelsResponseObject.List; - // CUSTOM: Recovered this field. See https://github.com/Azure/autorest.csharp/issues/4636. - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - /// Initializes a new instance of . /// /// is null. diff --git a/src/Custom/Models/OpenAIModelsModelFactory.cs b/src/Custom/Models/OpenAIModelsModelFactory.cs index 8413b55c8..61c75e6fb 100644 --- a/src/Custom/Models/OpenAIModelsModelFactory.cs +++ b/src/Custom/Models/OpenAIModelsModelFactory.cs @@ -12,10 +12,10 @@ public static partial class OpenAIModelsModelFactory public static ModelDeletionResult ModelDeletionResult(string modelId = null, bool deleted = default) { return new ModelDeletionResult( - modelId, deleted, + modelId, InternalDeleteModelResponseObject.Model, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } /// Initializes a new instance of . @@ -24,10 +24,10 @@ public static OpenAIModel OpenAIModel(string id = null, DateTimeOffset createdAt { return new OpenAIModel( id, - createdAt, - InternalModelObject.Model, ownedBy, - serializedAdditionalRawData: null); + InternalModelObject.Model, + createdAt, + additionalBinaryDataProperties: null); } /// Initializes a new instance of . diff --git a/src/Custom/Moderations/ModerationClient.Protocol.cs b/src/Custom/Moderations/ModerationClient.Protocol.cs index fec631bd2..38e140cc2 100644 --- a/src/Custom/Moderations/ModerationClient.Protocol.cs +++ b/src/Custom/Moderations/ModerationClient.Protocol.cs @@ -24,7 +24,7 @@ public virtual async Task ClassifyTextAsync(BinaryContent content, Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateModerationRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -41,6 +41,6 @@ public virtual ClientResult ClassifyText(BinaryContent content, RequestOptions o Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateModerationRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } } diff --git a/src/Custom/Moderations/ModerationClient.cs b/src/Custom/Moderations/ModerationClient.cs index d3912b28c..e66358c99 100644 --- a/src/Custom/Moderations/ModerationClient.cs +++ b/src/Custom/Moderations/ModerationClient.cs @@ -15,20 +15,14 @@ namespace OpenAI.Moderations; /// The service client for OpenAI moderation operations. [CodeGenClient("Moderations")] [CodeGenSuppress("ModerationClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateModerationAsync", typeof(ModerationOptions))] -[CodeGenSuppress("CreateModeration", typeof(ModerationOptions))] +[CodeGenSuppress("CreateModerationAsync", typeof(ModerationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateModeration", typeof(ModerationOptions), typeof(CancellationToken))] public partial class ModerationClient { private readonly string _model; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -41,7 +35,7 @@ public partial class ModerationClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// or is null. @@ -54,7 +48,7 @@ public partial class ModerationClient // - Added `model` parameter. // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The API key to authenticate with the service. /// The options to configure the client. @@ -67,7 +61,7 @@ public ModerationClient(string model, ApiKeyCredential credential, OpenAIClientO options ??= new OpenAIClientOptions(); _model = model; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -76,7 +70,7 @@ public ModerationClient(string model, ApiKeyCredential credential, OpenAIClientO // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The name of the model to use in requests sent to the service. To learn more about the available models, see . /// The options to configure the client. @@ -89,7 +83,7 @@ protected internal ModerationClient(ClientPipeline pipeline, string model, OpenA options ??= new OpenAIClientOptions(); _model = model; - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } @@ -105,9 +99,9 @@ public virtual async Task> ClassifyTextAsync(stri ModerationOptions options = new(); CreateModerationOptions(BinaryData.FromObjectAsJson(input), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await ClassifyTextAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((ModerationResultCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Classifies if the text input is potentially harmful across several categories. @@ -122,9 +116,9 @@ public virtual ClientResult ClassifyText(string input, Cancell ModerationOptions options = new(); CreateModerationOptions(BinaryData.FromObjectAsJson(input), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = ClassifyText(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(((ModerationResultCollection)result).FirstOrDefault(), result.GetRawResponse()); } /// Classifies if the text inputs are potentially harmful across several categories. @@ -139,9 +133,9 @@ public virtual async Task> ClassifyText ModerationOptions options = new(); CreateModerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = await ClassifyTextAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((ModerationResultCollection)result, result.GetRawResponse()); } /// Classifies if the text inputs are potentially harmful across several categories. @@ -156,9 +150,9 @@ public virtual ClientResult ClassifyText(IEnumerable ModerationOptions options = new(); CreateModerationOptions(BinaryData.FromObjectAsJson(inputs), ref options); - using BinaryContent content = options.ToBinaryContent(); + using BinaryContent content = options; ClientResult result = ClassifyText(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((ModerationResultCollection)result, result.GetRawResponse()); } private void CreateModerationOptions(BinaryData input, ref ModerationOptions options) diff --git a/src/Custom/Moderations/ModerationResult.Serialization.cs b/src/Custom/Moderations/ModerationResult.Serialization.cs index 2088857a5..b82fc4eb5 100644 --- a/src/Custom/Moderations/ModerationResult.Serialization.cs +++ b/src/Custom/Moderations/ModerationResult.Serialization.cs @@ -42,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter sexualMinors: SexualMinors.Flagged, violence: Violence.Flagged, violenceGraphic: ViolenceGraphic.Flagged, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); writer.WriteObjectValue(internalCategories, options); } if (SerializedAdditionalRawData?.ContainsKey("category_scores") != true) @@ -62,7 +62,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter sexualMinors: SexualMinors.Score, violence: Violence.Score, violenceGraphic: ViolenceGraphic.Score, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); writer.WriteObjectValue(internalCategoryScores, options); } if (SerializedAdditionalRawData?.ContainsKey("category_applied_input_types") != true) @@ -82,7 +82,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter sexualMinors: SexualMinors.ApplicableInputKinds.ToInternalApplicableInputKinds(), violence: Violence.ApplicableInputKinds.ToInternalApplicableInputKinds(), violenceGraphic: ViolenceGraphic.ApplicableInputKinds.ToInternalApplicableInputKinds(), - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); writer.WriteObjectValue(internalAppliedInputTypes, options); } if (SerializedAdditionalRawData != null) diff --git a/src/Custom/Moderations/ModerationResult.cs b/src/Custom/Moderations/ModerationResult.cs index 342aa2477..3a4694cb5 100644 --- a/src/Custom/Moderations/ModerationResult.cs +++ b/src/Custom/Moderations/ModerationResult.cs @@ -3,7 +3,7 @@ namespace OpenAI.Moderations; -// CUSTOM: +// CUSTOM: // - Removes the redundant classes `ModerationCategories` and `ModerationCategoryScores` and moves their properties into this type. [CodeGenModel("CreateModerationResponseResult")] [CodeGenSuppress("Categories")] @@ -13,8 +13,6 @@ namespace OpenAI.Moderations; [CodeGenSuppress(nameof(ModerationResult), typeof(bool), typeof(InternalModerationCategories), typeof(InternalModerationCategoryScores), typeof(InternalCreateModerationResponseResultCategoryAppliedInputTypes), typeof(IDictionary))] public partial class ModerationResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ModerationResult(bool flagged, ModerationCategory hate, ModerationCategory hateThreatening, ModerationCategory harassment, ModerationCategory harassmentThreatening, ModerationCategory illicit, ModerationCategory illicitViolent, ModerationCategory selfHarm, ModerationCategory selfHarmIntent, ModerationCategory selfHarmInstructions, ModerationCategory sexual, ModerationCategory sexualMinors, ModerationCategory violence, ModerationCategory violenceGraphic) { Flagged = flagged; diff --git a/src/Custom/Moderations/ModerationResultCollection.cs b/src/Custom/Moderations/ModerationResultCollection.cs index cc1f1ccc3..e21362f71 100644 --- a/src/Custom/Moderations/ModerationResultCollection.cs +++ b/src/Custom/Moderations/ModerationResultCollection.cs @@ -7,42 +7,10 @@ namespace OpenAI.Moderations; [CodeGenModel("CreateModerationResponse")] [CodeGenSuppress("Results")] [CodeGenSuppress(nameof(ModerationResultCollection))] -[CodeGenSuppress(nameof(ModerationResultCollection), typeof(string), typeof(string), typeof(IReadOnlyList))] +[CodeGenSuppress(nameof(ModerationResultCollection), typeof(string), typeof(string))] +[CodeGenSuppress(nameof(ModerationResultCollection), typeof(string), typeof(string), typeof(IDictionary))] public partial class ModerationResultCollection : ReadOnlyCollection { - // CUSTOM: Recovered this field. See https://github.com/Azure/autorest.csharp/issues/4636. - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary SerializedAdditionalRawData; - /// Initializes a new instance of . /// The unique identifier for the moderation request. /// The model used to generate the moderation results. diff --git a/src/Custom/OpenAIClient.cs b/src/Custom/OpenAIClient.cs index 32c92f89f..33b152ece 100644 --- a/src/Custom/OpenAIClient.cs +++ b/src/Custom/OpenAIClient.cs @@ -77,14 +77,8 @@ private static class KnownHeaderNames private readonly OpenAIClientOptions _options; - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public OpenAIClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -94,7 +88,7 @@ private static class KnownHeaderNames // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public OpenAIClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -104,7 +98,7 @@ private static class KnownHeaderNames // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// The options to configure the client. /// is null. @@ -114,13 +108,13 @@ public OpenAIClient(ApiKeyCredential credential, OpenAIClientOptions options) options ??= new OpenAIClientOptions(); _keyCredential = credential; - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); _options = options; } // CUSTOM: Added protected internal constructor that takes a ClientPipeline. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -129,7 +123,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); _options = options; } @@ -144,7 +138,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// /// A new . [Experimental("OPENAI001")] - public virtual AssistantClient GetAssistantClient() => new(_pipeline, _options); + public virtual AssistantClient GetAssistantClient() => new(Pipeline, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -155,7 +149,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual AudioClient GetAudioClient(string model) => new(_pipeline, model, _options); + public virtual AudioClient GetAudioClient(string model) => new(Pipeline, model, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -167,7 +161,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// /// A new . [Experimental("OPENAI001")] - public virtual BatchClient GetBatchClient() => new(_pipeline, _options); + public virtual BatchClient GetBatchClient() => new(Pipeline, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -178,7 +172,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual ChatClient GetChatClient(string model) => new(_pipeline, model, _options); + public virtual ChatClient GetChatClient(string model) => new(Pipeline, model, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -189,7 +183,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual EmbeddingClient GetEmbeddingClient(string model) => new(_pipeline, model, _options); + public virtual EmbeddingClient GetEmbeddingClient(string model) => new(Pipeline, model, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -200,7 +194,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual OpenAIFileClient GetOpenAIFileClient() => new(_pipeline, _options); + public virtual OpenAIFileClient GetOpenAIFileClient() => new(Pipeline, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -212,7 +206,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// /// A new . [Experimental("OPENAI001")] - public virtual FineTuningClient GetFineTuningClient() => new(_pipeline, _options); + public virtual FineTuningClient GetFineTuningClient() => new(Pipeline, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -223,7 +217,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual ImageClient GetImageClient(string model) => new(_pipeline, model, _options); + public virtual ImageClient GetImageClient(string model) => new(Pipeline, model, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -234,7 +228,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual OpenAIModelClient GetOpenAIModelClient() => new(_pipeline, _options); + public virtual OpenAIModelClient GetOpenAIModelClient() => new(Pipeline, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -245,7 +239,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// the same configuration details. /// /// A new . - public virtual ModerationClient GetModerationClient(string model) => new(_pipeline, model, _options); + public virtual ModerationClient GetModerationClient(string model) => new(Pipeline, model, _options); /// /// Gets a new instance of that reuses the client configuration details provided to @@ -257,7 +251,7 @@ protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions opt /// /// A new . [Experimental("OPENAI001")] - public virtual VectorStoreClient GetVectorStoreClient() => new(_pipeline, _options); + public virtual VectorStoreClient GetVectorStoreClient() => new(Pipeline, _options); [Experimental("OPENAI002")] public virtual RealtimeConversationClient GetRealtimeConversationClient(string model) => new(model, _keyCredential, _options); diff --git a/src/Custom/OpenAIError.cs b/src/Custom/OpenAIError.cs index ce82f6d7c..3199b5290 100644 --- a/src/Custom/OpenAIError.cs +++ b/src/Custom/OpenAIError.cs @@ -19,7 +19,7 @@ internal static OpenAIError TryCreateFromResponse(PipelineResponse response) { using JsonDocument errorDocument = JsonDocument.Parse(response.Content); OpenAIErrorResponse errorResponse - = OpenAIErrorResponse.DeserializeOpenAIErrorResponse(errorDocument.RootElement); + = OpenAIErrorResponse.DeserializeOpenAIErrorResponse(errorDocument.RootElement, null); return errorResponse.Error; } catch (InvalidOperationException) diff --git a/src/Custom/RealtimeConversation/ConversationContentPartKind.cs b/src/Custom/RealtimeConversation/ConversationContentPartKind.cs index fab135e12..75adf721b 100644 --- a/src/Custom/RealtimeConversation/ConversationContentPartKind.cs +++ b/src/Custom/RealtimeConversation/ConversationContentPartKind.cs @@ -9,8 +9,8 @@ namespace OpenAI.RealtimeConversation; public readonly partial struct ConversationContentPartKind { [CodeGenMember("Audio")] - public static ConversationContentPartKind OutputAudio { get; } = new(OutputAudioValue); + public static ConversationContentPartKind OutputAudio { get; } = new(AudioValue); [CodeGenMember("Text")] - public static ConversationContentPartKind OutputText { get; } = new(OutputTextValue); + public static ConversationContentPartKind OutputText { get; } = new(TextValue); } \ No newline at end of file diff --git a/src/Custom/RealtimeConversation/Internal/GeneratorStubs.cs b/src/Custom/RealtimeConversation/Internal/GeneratorStubs.cs index d88f51b6c..74c2eca27 100644 --- a/src/Custom/RealtimeConversation/Internal/GeneratorStubs.cs +++ b/src/Custom/RealtimeConversation/Internal/GeneratorStubs.cs @@ -36,6 +36,7 @@ namespace OpenAI.RealtimeConversation; [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeClientEvent")] internal partial class UnknownRealtimeClientEvent { } [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeContentPart")] internal partial class UnknownRealtimeContentPart { } [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeRequestItem")] internal partial class UnknownRealtimeRequestItem { } +[Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeRequestMessageItem")] internal partial class UnknownRealtimeRequestMessageItem { } [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeResponseItem")] internal partial class UnknownRealtimeResponseItem { } [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeResponseStatusDetails")] internal partial class UnknownRealtimeResponseStatusDetails { } [Experimental("OPENAI002")][CodeGenModel("UnknownRealtimeServerEvent")] internal partial class UnknownRealtimeServerEvent { } diff --git a/src/Custom/RealtimeConversation/Internal/InternalRealtimeClientEventResponseCreateResponse.cs b/src/Custom/RealtimeConversation/Internal/InternalRealtimeClientEventResponseCreateResponse.cs index 46a1d56ed..b4338272c 100644 --- a/src/Custom/RealtimeConversation/Internal/InternalRealtimeClientEventResponseCreateResponse.cs +++ b/src/Custom/RealtimeConversation/Internal/InternalRealtimeClientEventResponseCreateResponse.cs @@ -43,7 +43,7 @@ IList internalModalities toolChoice: toolChoice, temperature: sessionOptions.Temperature, maxOutputTokens: maxTokensChoice, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); return internalOptions; } } diff --git a/src/Custom/RealtimeConversation/RealtimeConversationClient.cs b/src/Custom/RealtimeConversation/RealtimeConversationClient.cs index 26ffb89e3..09a97f55f 100644 --- a/src/Custom/RealtimeConversation/RealtimeConversationClient.cs +++ b/src/Custom/RealtimeConversation/RealtimeConversationClient.cs @@ -9,9 +9,9 @@ namespace OpenAI.RealtimeConversation; [CodeGenClient("Realtime")] -[CodeGenSuppress("StartRealtimeSessionAsync", typeof(IEnumerable))] +[CodeGenSuppress("StartRealtimeSessionAsync", typeof(IEnumerable), typeof(CancellationToken))] [CodeGenSuppress("StartRealtimeSessionAsync", typeof(BinaryContent), typeof(RequestOptions))] -[CodeGenSuppress("StartRealtimeSession", typeof(IEnumerable))] +[CodeGenSuppress("StartRealtimeSession", typeof(IEnumerable), typeof(CancellationToken))] [CodeGenSuppress("StartRealtimeSession", typeof(BinaryContent), typeof(RequestOptions))] [CodeGenSuppress("CreateStartRealtimeSessionRequest", typeof(BinaryContent), typeof(RequestOptions))] [Experimental("OPENAI002")] @@ -20,7 +20,6 @@ public partial class RealtimeConversationClient public event EventHandler OnSendingCommand; public event EventHandler OnReceivingCommand; - private readonly Uri _endpoint; private readonly ApiKeyCredential _credential; /// diff --git a/src/Custom/RealtimeConversation/RealtimeConversationSession.cs b/src/Custom/RealtimeConversation/RealtimeConversationSession.cs index 61e8c9eaa..6ba3f6ab5 100644 --- a/src/Custom/RealtimeConversation/RealtimeConversationSession.cs +++ b/src/Custom/RealtimeConversation/RealtimeConversationSession.cs @@ -324,7 +324,7 @@ public virtual async IAsyncEnumerable ReceiveUpdatesAsync([E { await foreach (ClientResult protocolEvent in ReceiveUpdatesAsync(cancellationToken.ToRequestOptions())) { - ConversationUpdate nextUpdate = ConversationUpdate.FromResponse(protocolEvent.GetRawResponse()); + ConversationUpdate nextUpdate = (ConversationUpdate)protocolEvent; yield return nextUpdate; } } diff --git a/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartDeltaUpdate.cs b/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartDeltaUpdate.cs index fa0a9c0db..2d26b128f 100644 --- a/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartDeltaUpdate.cs +++ b/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartDeltaUpdate.cs @@ -72,7 +72,7 @@ public string FunctionArguments => _functionArgumentsDelta?.Delta; internal ConversationItemStreamingPartDeltaUpdate(ConversationUpdate baseUpdate) - : base(baseUpdate.Kind, baseUpdate.EventId, serializedAdditionalRawData: null) + : base(baseUpdate.EventId, baseUpdate.Kind, additionalBinaryDataProperties: null) { _contentPartAdded = baseUpdate as InternalRealtimeServerEventResponseContentPartAdded; _audioDelta = baseUpdate as InternalRealtimeServerEventResponseAudioDelta; diff --git a/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartFinishedUpdate.cs b/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartFinishedUpdate.cs index 085da7027..11636b082 100644 --- a/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartFinishedUpdate.cs +++ b/src/Custom/RealtimeConversation/ResponseUpdates/ConversationItemStreamingPartFinishedUpdate.cs @@ -42,7 +42,7 @@ public int ContentPartIndex internal ConversationItemStreamingPartFinishedUpdate(ConversationUpdate baseUpdate) - : base(baseUpdate.Kind, baseUpdate.EventId, serializedAdditionalRawData: null) + : base(baseUpdate.EventId, baseUpdate.Kind, additionalBinaryDataProperties: null) { _contentPartDone = baseUpdate as InternalRealtimeServerEventResponseContentPartDone; _functionCallArgumentsDone = baseUpdate as InternalRealtimeServerEventResponseFunctionCallArgumentsDone; diff --git a/src/Custom/VectorStores/AddFileToVectorStoreOperation.cs b/src/Custom/VectorStores/AddFileToVectorStoreOperation.cs index c0004a4d3..d160fb301 100644 --- a/src/Custom/VectorStores/AddFileToVectorStoreOperation.cs +++ b/src/Custom/VectorStores/AddFileToVectorStoreOperation.cs @@ -71,7 +71,7 @@ public static async Task RehydrateAsync(VectorSto ClientResult result = await client.GetFileAssociationAsync(token.VectorStoreId, token.FileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return client.CreateAddFileToVectorStoreOperation(ClientResult.FromValue(value, response)); } @@ -96,7 +96,7 @@ public static AddFileToVectorStoreOperation Rehydrate(VectorStoreClient client, ClientResult result = client.GetFileAssociation(token.VectorStoreId, token.FileId, cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return client.CreateAddFileToVectorStoreOperation(ClientResult.FromValue(value, response)); } @@ -107,7 +107,7 @@ public override async ValueTask UpdateStatusAsync(RequestOptions? ClientResult result = await GetFileAssociationAsync(options).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; ApplyUpdate(response, value); @@ -120,7 +120,7 @@ public override ClientResult UpdateStatus(RequestOptions? options = null) ClientResult result = GetFileAssociation(options); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; ApplyUpdate(response, value); @@ -167,7 +167,7 @@ public virtual async Task> GetFileAssoc { ClientResult result = await GetFileAssociationAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return ClientResult.FromValue(value, response); } @@ -181,7 +181,7 @@ public virtual ClientResult GetFileAssociation(Cance { ClientResult result = GetFileAssociation(cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return ClientResult.FromValue(value, response); } } diff --git a/src/Custom/VectorStores/CreateBatchFileJobOperation.cs b/src/Custom/VectorStores/CreateBatchFileJobOperation.cs index 59511d9f0..ad5acece8 100644 --- a/src/Custom/VectorStores/CreateBatchFileJobOperation.cs +++ b/src/Custom/VectorStores/CreateBatchFileJobOperation.cs @@ -74,7 +74,7 @@ public static async Task RehydrateAsync(VectorStore ClientResult result = await client.GetBatchFileJobAsync(token.VectorStoreId, token.BatchId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob job = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob job = (VectorStoreBatchFileJob) result; return client.CreateBatchFileJobOperation(ClientResult.FromValue(job, response)); } @@ -99,7 +99,7 @@ public static CreateBatchFileJobOperation Rehydrate(VectorStoreClient client, Co ClientResult result = client.GetBatchFileJob(token.VectorStoreId, token.BatchId, cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob job = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob job = (VectorStoreBatchFileJob) result; return client.CreateBatchFileJobOperation(ClientResult.FromValue(job, response)); } @@ -110,7 +110,7 @@ public override async ValueTask UpdateStatusAsync(RequestOptions? ClientResult result = await GetFileBatchAsync(options).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; ApplyUpdate(response, value); @@ -123,7 +123,7 @@ public override ClientResult UpdateStatus(RequestOptions? options = null) ClientResult result = GetFileBatch(options); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; ApplyUpdate(response, value); @@ -171,7 +171,7 @@ public virtual async Task> GetFileBatchAsy { ClientResult result = await GetFileBatchAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; return ClientResult.FromValue(value, response); } @@ -184,7 +184,7 @@ public virtual ClientResult GetFileBatch(CancellationTo { ClientResult result = GetFileBatch(cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; return ClientResult.FromValue(value, response); } @@ -197,7 +197,7 @@ public virtual async Task> CancelAsync(Can { ClientResult result = await CancelAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; return ClientResult.FromValue(value, response); } @@ -210,7 +210,7 @@ public virtual ClientResult Cancel(CancellationToken ca { ClientResult result = Cancel(cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob) result; return ClientResult.FromValue(value, response); } } \ No newline at end of file diff --git a/src/Custom/VectorStores/CreateVectorStoreOperation.cs b/src/Custom/VectorStores/CreateVectorStoreOperation.cs index 1171fd076..d140e7473 100644 --- a/src/Custom/VectorStores/CreateVectorStoreOperation.cs +++ b/src/Custom/VectorStores/CreateVectorStoreOperation.cs @@ -66,7 +66,7 @@ public static async Task RehydrateAsync(VectorStoreC ClientResult result = await client.GetVectorStoreAsync(token.VectorStoreId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStore vectorStore = VectorStore.FromResponse(response); + VectorStore vectorStore = (VectorStore)result; return client.CreateCreateVectorStoreOperation(ClientResult.FromValue(vectorStore, response)); } @@ -91,7 +91,7 @@ public static CreateVectorStoreOperation Rehydrate(VectorStoreClient client, Con ClientResult result = client.GetVectorStore(token.VectorStoreId, cancellationToken.ToRequestOptions()); PipelineResponse response = result.GetRawResponse(); - VectorStore vectorStore = VectorStore.FromResponse(response); + VectorStore vectorStore = (VectorStore)result; return client.CreateCreateVectorStoreOperation(ClientResult.FromValue(vectorStore, response)); } @@ -102,7 +102,7 @@ public override async ValueTask UpdateStatusAsync(RequestOptions? ClientResult result = await GetVectorStoreAsync(options).ConfigureAwait(false); PipelineResponse response = result.GetRawResponse(); - VectorStore value = VectorStore.FromResponse(response); + VectorStore value = (VectorStore)result; ApplyUpdate(response, value); @@ -115,7 +115,7 @@ public override ClientResult UpdateStatus(RequestOptions? options = null) ClientResult result = GetVectorStore(options); PipelineResponse response = result.GetRawResponse(); - VectorStore value = VectorStore.FromResponse(response); + VectorStore value = (VectorStore)result; ApplyUpdate(response, value); @@ -161,7 +161,7 @@ public virtual async Task> GetVectorStoreAsync(Cancell ClientResult result = await GetVectorStoreAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); return ClientResult.FromValue( - VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + (VectorStore)result, result.GetRawResponse()); } /// @@ -172,6 +172,6 @@ ClientResult result public virtual ClientResult GetVectorStore(CancellationToken cancellationToken = default) { ClientResult result = GetVectorStore(cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((VectorStore)result, result.GetRawResponse()); } } diff --git a/src/Custom/VectorStores/VectorStoreClient.Protocol.cs b/src/Custom/VectorStores/VectorStoreClient.Protocol.cs index b27f330c4..810460b8d 100644 --- a/src/Custom/VectorStores/VectorStoreClient.Protocol.cs +++ b/src/Custom/VectorStores/VectorStoreClient.Protocol.cs @@ -2,12 +2,15 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.ComponentModel; +using System.Text.Json; using System.Threading.Tasks; namespace OpenAI.VectorStores; -[CodeGenSuppress("GetVectorStoreFilesAsync", typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetVectorStoreFiles", typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListVectorStoresAsync", typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListVectorStores", typeof(int?), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListVectorStoreFilesAsync", typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListVectorStoreFiles", typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CreateVectorStoreFileAsync", typeof(string), typeof(BinaryContent), typeof(RequestOptions))] [CodeGenSuppress("CreateVectorStoreFile", typeof(string), typeof(BinaryContent), typeof(RequestOptions))] [CodeGenSuppress("GetVectorStoreFileAsync", typeof(string), typeof(string), typeof(RequestOptions))] @@ -20,8 +23,10 @@ namespace OpenAI.VectorStores; [CodeGenSuppress("GetVectorStoreFileBatch", typeof(string), typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CancelVectorStoreFileBatchAsync", typeof(string), typeof(string), typeof(RequestOptions))] [CodeGenSuppress("CancelVectorStoreFileBatch", typeof(string), typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetFilesInVectorStoreBatchesAsync", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] -[CodeGenSuppress("GetFilesInVectorStoreBatches", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFilesInVectorStoreBatchAsync", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFilesInVectorStoreBatch", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFilesInVectorStoreBatchesAsync", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] +[CodeGenSuppress("ListFilesInVectorStoreBatches", typeof(string), typeof(string), typeof(int?), typeof(string), typeof(string), typeof(string), typeof(string), typeof(RequestOptions))] public partial class VectorStoreClient { /// @@ -51,7 +56,7 @@ public partial class VectorStoreClient [EditorBrowsable(EditorBrowsableState.Never)] public virtual AsyncCollectionResult GetVectorStoresAsync(int? limit, string order, string after, string before, RequestOptions options) { - return new AsyncVectorStoreCollectionResult(this, _pipeline, options, limit, order, after, before); + return new AsyncVectorStoreCollectionResult(this, Pipeline, options, limit, order, after, before); } /// @@ -81,7 +86,7 @@ public virtual AsyncCollectionResult GetVectorStoresAsync(int? limit, string ord [EditorBrowsable(EditorBrowsableState.Never)] public virtual CollectionResult GetVectorStores(int? limit, string order, string after, string before, RequestOptions options) { - return new VectorStoreCollectionResult(this, _pipeline, options, limit, order, after, before); + return new VectorStoreCollectionResult(this, Pipeline, options, limit, order, after, before); } /// @@ -101,8 +106,9 @@ public virtual CollectionResult GetVectorStores(int? limit, string order, string public virtual async Task CreateVectorStoreAsync(BinaryContent content, bool waitUntilCompleted, RequestOptions options = null) { using PipelineMessage message = CreateCreateVectorStoreRequest(content, options); - PipelineResponse response = await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); - VectorStore value = VectorStore.FromResponse(response); + PipelineResponse response = await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStore value = VectorStore.DeserializeVectorStore(document.RootElement, ModelSerializationExtensions.WireOptions); CreateVectorStoreOperation operation = this.CreateCreateVectorStoreOperation(ClientResult.FromValue(value, response)); return await operation.WaitUntilAsync(waitUntilCompleted, options).ConfigureAwait(false); @@ -125,8 +131,9 @@ public virtual async Task CreateVectorStoreAsync(Bin public virtual CreateVectorStoreOperation CreateVectorStore(BinaryContent content, bool waitUntilCompleted, RequestOptions options = null) { using PipelineMessage message = CreateCreateVectorStoreRequest(content, options); - PipelineResponse response = _pipeline.ProcessMessage(message, options); - VectorStore value = VectorStore.FromResponse(response); + PipelineResponse response = Pipeline.ProcessMessage(message, options); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStore value = VectorStore.DeserializeVectorStore(document.RootElement, ModelSerializationExtensions.WireOptions); CreateVectorStoreOperation operation = this.CreateCreateVectorStoreOperation(ClientResult.FromValue(value, response)); return operation.WaitUntil(waitUntilCompleted, options); @@ -146,7 +153,7 @@ internal virtual async Task GetVectorStoreAsync(string vectorStore Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); using PipelineMessage message = CreateGetVectorStoreRequest(vectorStoreId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -163,7 +170,7 @@ internal virtual ClientResult GetVectorStore(string vectorStoreId, RequestOption Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); using PipelineMessage message = CreateGetVectorStoreRequest(vectorStoreId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -183,7 +190,7 @@ public virtual async Task ModifyVectorStoreAsync(string vectorStor Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -203,7 +210,7 @@ public virtual ClientResult ModifyVectorStore(string vectorStoreId, BinaryConten Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -221,7 +228,7 @@ public virtual async Task DeleteVectorStoreAsync(string vectorStor Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); using PipelineMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -239,7 +246,7 @@ public virtual ClientResult DeleteVectorStore(string vectorStoreId, RequestOptio Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); using PipelineMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -275,7 +282,7 @@ public virtual AsyncCollectionResult GetFileAssociationsAsync(string vectorStore { Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - return new AsyncVectorStoreFileCollectionResult(this, _pipeline, options, vectorStoreId, limit, order, after, before, filter); + return new AsyncVectorStoreFileCollectionResult(this, Pipeline, options, vectorStoreId, limit, order, after, before, filter); } /// @@ -311,7 +318,7 @@ public virtual CollectionResult GetFileAssociations(string vectorStoreId, int? l { Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - return new VectorStoreFileCollectionResult(this, _pipeline, options, vectorStoreId, limit, order, after, before, filter); + return new VectorStoreFileCollectionResult(this, Pipeline, options, vectorStoreId, limit, order, after, before, filter); } @@ -337,8 +344,9 @@ public virtual async Task AddFileToVectorStoreAsy Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, options); - PipelineResponse response = await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + PipelineResponse response = await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStoreFileAssociation value = VectorStoreFileAssociation.DeserializeVectorStoreFileAssociation(document.RootElement, ModelSerializationExtensions.WireOptions); AddFileToVectorStoreOperation operation = this.CreateAddFileToVectorStoreOperation(ClientResult.FromValue(value, response)); return await operation.WaitUntilAsync(waitUntilCompleted, options).ConfigureAwait(false); @@ -366,8 +374,9 @@ public virtual AddFileToVectorStoreOperation AddFileToVectorStore(string vectorS Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, options); - PipelineResponse response = _pipeline.ProcessMessage(message, options); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + PipelineResponse response = Pipeline.ProcessMessage(message, options); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStoreFileAssociation value = VectorStoreFileAssociation.DeserializeVectorStoreFileAssociation(document.RootElement, ModelSerializationExtensions.WireOptions); AddFileToVectorStoreOperation operation = this.CreateAddFileToVectorStoreOperation(ClientResult.FromValue(value, response)); return operation.WaitUntil(waitUntilCompleted, options); @@ -390,7 +399,7 @@ public virtual async Task GetFileAssociationAsync(string vectorSto Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -410,7 +419,7 @@ public virtual ClientResult GetFileAssociation(string vectorStoreId, string file Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -430,7 +439,7 @@ public virtual async Task CancelBatchFileJobAsync(string vectorSto Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -450,7 +459,7 @@ public virtual ClientResult CancelBatchFileJob(string vectorStoreId, string batc Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -488,7 +497,7 @@ public virtual AsyncCollectionResult GetFileAssociationsAsync(string vectorStore Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - return new AsyncVectorStoreFileBatchCollectionResult(this, _pipeline, options, vectorStoreId, batchId, limit, order, after, before, filter); + return new AsyncVectorStoreFileBatchCollectionResult(this, Pipeline, options, vectorStoreId, batchId, limit, order, after, before, filter); } /// @@ -526,7 +535,7 @@ public virtual CollectionResult GetFileAssociations(string vectorStoreId, string Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - return new VectorStoreFileBatchCollectionResult(this, _pipeline, options, vectorStoreId, batchId, limit, order, after, before, filter); + return new VectorStoreFileBatchCollectionResult(this, Pipeline, options, vectorStoreId, batchId, limit, order, after, before, filter); } /// @@ -546,7 +555,7 @@ public virtual async Task RemoveFileFromStoreAsync(string vectorSt Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -566,7 +575,7 @@ public virtual ClientResult RemoveFileFromStore(string vectorStoreId, string fil Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); using PipelineMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } /// @@ -595,8 +604,9 @@ public virtual async Task CreateBatchFileJobAsync( Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, options); - PipelineResponse response = await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); - VectorStoreBatchFileJob job = VectorStoreBatchFileJob.FromResponse(response); + PipelineResponse response = await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStoreBatchFileJob job = VectorStoreBatchFileJob.DeserializeVectorStoreBatchFileJob(document.RootElement, ModelSerializationExtensions.WireOptions); CreateBatchFileJobOperation operation = this.CreateBatchFileJobOperation(ClientResult.FromValue(job, response)); return await operation.WaitUntilAsync(waitUntilCompleted, options).ConfigureAwait(false); @@ -628,8 +638,9 @@ public virtual CreateBatchFileJobOperation CreateBatchFileJob( Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, options); - PipelineResponse response = _pipeline.ProcessMessage(message, options); - VectorStoreBatchFileJob job = VectorStoreBatchFileJob.FromResponse(response); + PipelineResponse response = Pipeline.ProcessMessage(message, options); + using JsonDocument document = JsonDocument.Parse(response.Content); + VectorStoreBatchFileJob job = VectorStoreBatchFileJob.DeserializeVectorStoreBatchFileJob(document.RootElement, ModelSerializationExtensions.WireOptions); CreateBatchFileJobOperation operation = this.CreateBatchFileJobOperation(ClientResult.FromValue(job, response)); return operation.WaitUntil(waitUntilCompleted, options); @@ -651,7 +662,7 @@ internal virtual async Task GetBatchFileJobAsync(string vectorStor Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } /// @@ -670,12 +681,12 @@ internal virtual ClientResult GetBatchFileJob(string vectorStoreId, string batch Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); using PipelineMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } internal virtual PipelineMessage CreateCreateVectorStoreRequest(BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -692,7 +703,7 @@ internal virtual PipelineMessage CreateCreateVectorStoreRequest(BinaryContent co internal virtual PipelineMessage CreateGetVectorStoresRequest(int? limit, string order, string after, string before, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -723,7 +734,7 @@ internal virtual PipelineMessage CreateGetVectorStoresRequest(int? limit, string internal virtual PipelineMessage CreateGetVectorStoreRequest(string vectorStoreId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -739,7 +750,7 @@ internal virtual PipelineMessage CreateGetVectorStoreRequest(string vectorStoreI internal virtual PipelineMessage CreateModifyVectorStoreRequest(string vectorStoreId, BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -757,7 +768,7 @@ internal virtual PipelineMessage CreateModifyVectorStoreRequest(string vectorSto internal virtual PipelineMessage CreateDeleteVectorStoreRequest(string vectorStoreId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "DELETE"; @@ -773,7 +784,7 @@ internal virtual PipelineMessage CreateDeleteVectorStoreRequest(string vectorSto internal virtual PipelineMessage CreateGetVectorStoreFilesRequest(string vectorStoreId, int? limit, string order, string after, string before, string filter, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -810,7 +821,7 @@ internal virtual PipelineMessage CreateGetVectorStoreFilesRequest(string vectorS internal virtual PipelineMessage CreateCreateVectorStoreFileRequest(string vectorStoreId, BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -829,7 +840,7 @@ internal virtual PipelineMessage CreateCreateVectorStoreFileRequest(string vecto internal virtual PipelineMessage CreateDeleteVectorStoreFileRequest(string vectorStoreId, string fileId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "DELETE"; @@ -847,7 +858,7 @@ internal virtual PipelineMessage CreateDeleteVectorStoreFileRequest(string vecto internal virtual PipelineMessage CreateCancelVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -866,7 +877,7 @@ internal virtual PipelineMessage CreateCancelVectorStoreFileBatchRequest(string internal virtual PipelineMessage CreateCreateVectorStoreFileBatchRequest(string vectorStoreId, BinaryContent content, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "POST"; @@ -885,7 +896,7 @@ internal virtual PipelineMessage CreateCreateVectorStoreFileBatchRequest(string internal virtual PipelineMessage CreateGetVectorStoreFileRequest(string vectorStoreId, string fileId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -903,7 +914,7 @@ internal virtual PipelineMessage CreateGetVectorStoreFileRequest(string vectorSt internal virtual PipelineMessage CreateGetVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; @@ -921,7 +932,7 @@ internal virtual PipelineMessage CreateGetVectorStoreFileBatchRequest(string vec internal virtual PipelineMessage CreateGetFilesInVectorStoreBatchesRequest(string vectorStoreId, string batchId, int? limit, string order, string after, string before, string filter, RequestOptions options) { - var message = _pipeline.CreateMessage(); + var message = Pipeline.CreateMessage(); message.ResponseClassifier = PipelineMessageClassifier200; var request = message.Request; request.Method = "GET"; diff --git a/src/Custom/VectorStores/VectorStoreClient.cs b/src/Custom/VectorStores/VectorStoreClient.cs index 07fcbc145..5f42766e6 100644 --- a/src/Custom/VectorStores/VectorStoreClient.cs +++ b/src/Custom/VectorStores/VectorStoreClient.cs @@ -15,42 +15,30 @@ namespace OpenAI.VectorStores; [Experimental("OPENAI001")] [CodeGenClient("VectorStores")] [CodeGenSuppress("VectorStoreClient", typeof(ClientPipeline), typeof(ApiKeyCredential), typeof(Uri))] -[CodeGenSuppress("CreateVectorStoreAsync", typeof(VectorStoreCreationOptions))] -[CodeGenSuppress("CreateVectorStore", typeof(VectorStoreCreationOptions))] -[CodeGenSuppress("GetVectorStoreAsync", typeof(string))] -[CodeGenSuppress("GetVectorStore", typeof(string))] -[CodeGenSuppress("ModifyVectorStoreAsync", typeof(string), typeof(VectorStoreModificationOptions))] -[CodeGenSuppress("ModifyVectorStore", typeof(string), typeof(VectorStoreModificationOptions))] -[CodeGenSuppress("DeleteVectorStoreAsync", typeof(string))] -[CodeGenSuppress("DeleteVectorStore", typeof(string))] -[CodeGenSuppress("GetVectorStoresAsync", typeof(int?), typeof(VectorStoreCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetVectorStores", typeof(int?), typeof(VectorStoreCollectionOrder?), typeof(string), typeof(string))] -[CodeGenSuppress("GetVectorStoreFilesAsync", typeof(string), typeof(int?), typeof(VectorStoreFileAssociationCollectionOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?))] -[CodeGenSuppress("GetVectorStoreFiles", typeof(string), typeof(int?), typeof(VectorStoreFileAssociationCollectionOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?))] -[CodeGenSuppress("CreateVectorStoreFileAsync", typeof(string), typeof(InternalCreateVectorStoreFileRequest))] -[CodeGenSuppress("CreateVectorStoreFile", typeof(string), typeof(InternalCreateVectorStoreFileRequest))] -[CodeGenSuppress("GetVectorStoreFileAsync", typeof(string), typeof(string))] -[CodeGenSuppress("GetVectorStoreFile", typeof(string), typeof(string))] -[CodeGenSuppress("DeleteVectorStoreFileAsync", typeof(string), typeof(string))] -[CodeGenSuppress("DeleteVectorStoreFile", typeof(string), typeof(string))] -[CodeGenSuppress("CreateVectorStoreFileBatchAsync", typeof(string), typeof(InternalCreateVectorStoreFileBatchRequest))] -[CodeGenSuppress("CreateVectorStoreFileBatch", typeof(string), typeof(InternalCreateVectorStoreFileBatchRequest))] -[CodeGenSuppress("GetVectorStoreFileBatchAsync", typeof(string), typeof(string))] -[CodeGenSuppress("GetVectorStoreFileBatch", typeof(string), typeof(string))] -[CodeGenSuppress("CancelVectorStoreFileBatchAsync", typeof(string), typeof(string))] -[CodeGenSuppress("CancelVectorStoreFileBatch", typeof(string), typeof(string))] -[CodeGenSuppress("GetFilesInVectorStoreBatchesAsync", typeof(string), typeof(string), typeof(int?), typeof(InternalListFilesInVectorStoreBatchRequestOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?))] -[CodeGenSuppress("GetFilesInVectorStoreBatches", typeof(string), typeof(string), typeof(int?), typeof(InternalListFilesInVectorStoreBatchRequestOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?))] +[CodeGenSuppress("CreateVectorStoreAsync", typeof(VectorStoreCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("CreateVectorStore", typeof(VectorStoreCreationOptions), typeof(CancellationToken))] +[CodeGenSuppress("ListVectorStoresAsync", typeof(int?), typeof(VectorStoreCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListVectorStores", typeof(int?), typeof(VectorStoreCollectionOrder?), typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListVectorStoreFilesAsync", typeof(string), typeof(int?), typeof(VectorStoreFileAssociationCollectionOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?), typeof(CancellationToken))] +[CodeGenSuppress("ListVectorStoreFiles", typeof(string), typeof(int?), typeof(VectorStoreFileAssociationCollectionOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?), typeof(CancellationToken))] +[CodeGenSuppress("CreateVectorStoreFileAsync", typeof(string), typeof(InternalCreateVectorStoreFileRequest), typeof(CancellationToken))] +[CodeGenSuppress("CreateVectorStoreFile", typeof(string), typeof(InternalCreateVectorStoreFileRequest), typeof(CancellationToken))] +[CodeGenSuppress("GetVectorStoreFileAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetVectorStoreFile", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("DeleteVectorStoreFileAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("DeleteVectorStoreFile", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CreateVectorStoreFileBatchAsync", typeof(string), typeof(InternalCreateVectorStoreFileBatchRequest), typeof(CancellationToken))] +[CodeGenSuppress("CreateVectorStoreFileBatch", typeof(string), typeof(InternalCreateVectorStoreFileBatchRequest), typeof(CancellationToken))] +[CodeGenSuppress("GetVectorStoreFileBatchAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("GetVectorStoreFileBatch", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelVectorStoreFileBatchAsync", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("CancelVectorStoreFileBatch", typeof(string), typeof(string), typeof(CancellationToken))] +[CodeGenSuppress("ListFilesInVectorStoreBatchAsync", typeof(string), typeof(string), typeof(int?), typeof(InternalListFilesInVectorStoreBatchRequestOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?), typeof(CancellationToken))] +[CodeGenSuppress("ListFilesInVectorStoreBatch", typeof(string), typeof(string), typeof(int?), typeof(InternalListFilesInVectorStoreBatchRequestOrder?), typeof(string), typeof(string), typeof(VectorStoreFileStatusFilter?), typeof(CancellationToken))] public partial class VectorStoreClient { - // CUSTOM: Remove virtual keyword. - /// - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// - public ClientPipeline Pipeline => _pipeline; - // CUSTOM: Added as a convenience. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public VectorStoreClient(string apiKey) : this(new ApiKeyCredential(apiKey), new OpenAIClientOptions()) @@ -60,7 +48,7 @@ public partial class VectorStoreClient // CUSTOM: // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The API key to authenticate with the service. /// is null. public VectorStoreClient(ApiKeyCredential credential) : this(credential, new OpenAIClientOptions()) @@ -78,7 +66,7 @@ public VectorStoreClient(ApiKeyCredential credential, OpenAIClientOptions option Argument.AssertNotNull(credential, nameof(credential)); options ??= new OpenAIClientOptions(); - _pipeline = OpenAIClient.CreatePipeline(credential, options); + Pipeline = OpenAIClient.CreatePipeline(credential, options); _endpoint = OpenAIClient.GetEndpoint(options); } @@ -86,7 +74,7 @@ public VectorStoreClient(ApiKeyCredential credential, OpenAIClientOptions option // - Used a custom pipeline. // - Demoted the endpoint parameter to be a property in the options class. // - Made protected. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The HTTP pipeline to send and receive REST requests and responses. /// The options to configure the client. /// is null. @@ -95,13 +83,13 @@ protected internal VectorStoreClient(ClientPipeline pipeline, OpenAIClientOption Argument.AssertNotNull(pipeline, nameof(pipeline)); options ??= new OpenAIClientOptions(); - _pipeline = pipeline; + Pipeline = pipeline; _endpoint = OpenAIClient.GetEndpoint(options); } internal virtual CreateVectorStoreOperation CreateCreateVectorStoreOperation(ClientResult result) { - return new CreateVectorStoreOperation(_pipeline, _endpoint, result); + return new CreateVectorStoreOperation(Pipeline, _endpoint, result); } internal virtual AddFileToVectorStoreOperation CreateAddFileToVectorStoreOperation(ClientResult result) @@ -122,11 +110,11 @@ internal virtual CreateBatchFileJobOperation CreateBatchFileJobOperation(ClientR /// The to use. /// A token that can be used to cancel this method call. /// is null. - /// A that can be used to wait for + /// A that can be used to wait for /// the vector store creation to complete. public virtual async Task CreateVectorStoreAsync(bool waitUntilCompleted, VectorStoreCreationOptions vectorStore = null, CancellationToken cancellationToken = default) { - using BinaryContent content = vectorStore?.ToBinaryContent(); + using BinaryContent content = vectorStore; return await CreateVectorStoreAsync(content, waitUntilCompleted, cancellationToken.ToRequestOptions()).ConfigureAwait(false); } @@ -138,11 +126,11 @@ public virtual async Task CreateVectorStoreAsync(boo /// The to use. /// A token that can be used to cancel this method call. /// is null. - /// A that can be used to wait for + /// A that can be used to wait for /// the vector store creation to complete. public virtual CreateVectorStoreOperation CreateVectorStore(bool waitUntilCompleted, VectorStoreCreationOptions vectorStore = null, CancellationToken cancellationToken = default) { - using BinaryContent content = vectorStore?.ToBinaryContent(); + using BinaryContent content = vectorStore; return CreateVectorStore(content, waitUntilCompleted, cancellationToken.ToRequestOptions()); } @@ -159,7 +147,7 @@ internal virtual async Task> GetVectorStoreAsync(strin ClientResult result = await GetVectorStoreAsync(vectorStoreId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); return ClientResult.FromValue( - VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + (VectorStore)result, result.GetRawResponse()); } /// @@ -173,7 +161,7 @@ public virtual ClientResult GetVectorStore(string vectorStoreId, Ca Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); ClientResult result = GetVectorStore(vectorStoreId, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((VectorStore)result, result.GetRawResponse()); } /// @@ -188,9 +176,9 @@ public virtual async Task> ModifyVectorStoreAsync(stri Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(vectorStore, nameof(vectorStore)); - using BinaryContent content = vectorStore.ToBinaryContent(); + using BinaryContent content = vectorStore; ClientResult result = await ModifyVectorStoreAsync(vectorStoreId, content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((VectorStore)result, result.GetRawResponse()); } /// @@ -205,9 +193,9 @@ public virtual ClientResult ModifyVectorStore(string vectorStoreId, Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(vectorStore, nameof(vectorStore)); - using BinaryContent content = vectorStore.ToBinaryContent(); + using BinaryContent content = vectorStore; ClientResult result = ModifyVectorStore(vectorStoreId, content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(VectorStore.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue((VectorStore)result, result.GetRawResponse()); } /// @@ -222,7 +210,7 @@ public virtual async Task> DeleteVectorS ClientResult protocolResult = await DeleteVectorStoreAsync(vectorStoreId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse rawProtocolResponse = protocolResult?.GetRawResponse(); - VectorStoreDeletionResult value = VectorStoreDeletionResult.FromResponse(rawProtocolResponse); + VectorStoreDeletionResult value = (VectorStoreDeletionResult)protocolResult; return ClientResult.FromValue(value, rawProtocolResponse); } @@ -238,7 +226,7 @@ public virtual ClientResult DeleteVectorStore(string ClientResult protocolResult = DeleteVectorStore(vectorStoreId, cancellationToken.ToRequestOptions()); PipelineResponse rawProtocolResponse = protocolResult?.GetRawResponse(); - VectorStoreDeletionResult value = VectorStoreDeletionResult.FromResponse(rawProtocolResponse); + VectorStoreDeletionResult value = (VectorStoreDeletionResult)protocolResult; return ClientResult.FromValue(value, rawProtocolResponse); } @@ -314,7 +302,7 @@ public virtual CollectionResult GetVectorStores( /// The ID of the vector store to associate the file with. /// The ID of the file to associate with the vector store. /// A token that can be used to cancel this method call. - /// A that can be used to wait for + /// A that can be used to wait for /// the vector store file addition to complete. /// or is null. public virtual async Task AddFileToVectorStoreAsync(string vectorStoreId, string fileId, bool waitUntilCompleted, CancellationToken cancellationToken = default) @@ -323,7 +311,7 @@ public virtual async Task AddFileToVectorStoreAsy Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); InternalCreateVectorStoreFileRequest internalRequest = new(fileId); - return await AddFileToVectorStoreAsync(vectorStoreId, internalRequest.ToBinaryContent(), waitUntilCompleted, cancellationToken.ToRequestOptions()).ConfigureAwait(false); + return await AddFileToVectorStoreAsync(vectorStoreId, internalRequest, waitUntilCompleted, cancellationToken.ToRequestOptions()).ConfigureAwait(false); } /// @@ -336,7 +324,7 @@ public virtual async Task AddFileToVectorStoreAsy /// The ID of the vector store to associate the file with. /// The ID of the file to associate with the vector store. /// A token that can be used to cancel this method call. - /// A that can be used to wait for + /// A that can be used to wait for /// the vector store file addition to complete. /// or is null. public virtual AddFileToVectorStoreOperation AddFileToVectorStore(string vectorStoreId, string fileId, bool waitUntilCompleted, CancellationToken cancellationToken = default) @@ -345,7 +333,7 @@ public virtual AddFileToVectorStoreOperation AddFileToVectorStore(string vectorS Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); InternalCreateVectorStoreFileRequest internalRequest = new(fileId); - return AddFileToVectorStore(vectorStoreId, internalRequest.ToBinaryContent(), waitUntilCompleted, cancellationToken.ToRequestOptions()); + return AddFileToVectorStore(vectorStoreId, internalRequest, waitUntilCompleted, cancellationToken.ToRequestOptions()); } /// @@ -442,7 +430,7 @@ public virtual async Task> GetFileAssoc ClientResult result = await GetFileAssociationAsync(vectorStoreId, fileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result?.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return ClientResult.FromValue(value, response); } @@ -464,7 +452,7 @@ public virtual ClientResult GetFileAssociation( ClientResult result = GetFileAssociation(vectorStoreId, fileId, cancellationToken.ToRequestOptions()); PipelineResponse response = result?.GetRawResponse(); - VectorStoreFileAssociation value = VectorStoreFileAssociation.FromResponse(response); + VectorStoreFileAssociation value = (VectorStoreFileAssociation)result; return ClientResult.FromValue(value, response); } @@ -483,7 +471,7 @@ public virtual async Task> RemoveFileFr { ClientResult protocolResult = await RemoveFileFromStoreAsync(vectorStoreId, fileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse protocolResponse = protocolResult?.GetRawResponse(); - FileFromStoreRemovalResult value = FileFromStoreRemovalResult.FromResponse(protocolResponse); + FileFromStoreRemovalResult value = (FileFromStoreRemovalResult)protocolResult; return ClientResult.FromValue(value, protocolResponse); } @@ -502,7 +490,7 @@ public virtual ClientResult RemoveFileFromStore(stri { ClientResult protocolResult = RemoveFileFromStore(vectorStoreId, fileId, cancellationToken.ToRequestOptions()); PipelineResponse protocolResponse = protocolResult?.GetRawResponse(); - FileFromStoreRemovalResult value = FileFromStoreRemovalResult.FromResponse(protocolResponse); + FileFromStoreRemovalResult value = (FileFromStoreRemovalResult)protocolResult; return ClientResult.FromValue(value, protocolResponse); } @@ -516,7 +504,7 @@ public virtual ClientResult RemoveFileFromStore(stri /// The ID of the vector store to associate files with. /// The IDs of the files to associate with the vector store. /// A token that can be used to cancel this method call. - /// A that can be used to wait for + /// A that can be used to wait for /// the operation to complete, get information about the batch file job, or cancel the operation. public virtual async Task CreateBatchFileJobAsync( string vectorStoreId, @@ -527,7 +515,7 @@ public virtual async Task CreateBatchFileJobAsync( Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNullOrEmpty(fileIds, nameof(fileIds)); - BinaryContent content = new InternalCreateVectorStoreFileBatchRequest(fileIds).ToBinaryContent(); + BinaryContent content = new InternalCreateVectorStoreFileBatchRequest(fileIds); RequestOptions options = cancellationToken.ToRequestOptions(); return await CreateBatchFileJobAsync(vectorStoreId, content, waitUntilCompleted, options).ConfigureAwait(false); @@ -543,7 +531,7 @@ public virtual async Task CreateBatchFileJobAsync( /// The ID of the vector store to associate files with. /// The IDs of the files to associate with the vector store. /// A token that can be used to cancel this method call. - /// A that can be used to wait for + /// A that can be used to wait for /// the operation to complete, get information about the batch file job, or cancel the operation. public virtual CreateBatchFileJobOperation CreateBatchFileJob( string vectorStoreId, @@ -554,7 +542,7 @@ public virtual CreateBatchFileJobOperation CreateBatchFileJob( Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNullOrEmpty(fileIds, nameof(fileIds)); - BinaryContent content = new InternalCreateVectorStoreFileBatchRequest(fileIds).ToBinaryContent(); + BinaryContent content = new InternalCreateVectorStoreFileBatchRequest(fileIds); RequestOptions options = cancellationToken.ToRequestOptions(); return CreateBatchFileJob(vectorStoreId, content, waitUntilCompleted, options); @@ -707,7 +695,7 @@ public virtual async Task> GetBatchFileJob ClientResult result = await GetBatchFileJobAsync(vectorStoreId, batchJobId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result?.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob)result; return ClientResult.FromValue(value, response); } @@ -725,7 +713,7 @@ public virtual ClientResult GetBatchFileJob(string vect ClientResult result = GetBatchFileJob(vectorStoreId, batchJobId, cancellationToken.ToRequestOptions()); PipelineResponse response = result?.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob)result; return ClientResult.FromValue(value, response); } @@ -736,7 +724,7 @@ public virtual ClientResult GetBatchFileJob(string vect /// The ID of the that is the ingestion target of the batch job being cancelled. /// /// - /// The ID of the that should be canceled. + /// The ID of the that should be canceled. /// /// A token that can be used to cancel this method call. /// An updated instance. @@ -747,7 +735,7 @@ public virtual async Task> CancelBatchFile ClientResult result = await CancelBatchFileJobAsync(vectorStoreId, batchJobId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); PipelineResponse response = result?.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob)result; return ClientResult.FromValue(value, response); } @@ -758,7 +746,7 @@ public virtual async Task> CancelBatchFile /// The ID of the that is the ingestion target of the batch job being cancelled. /// /// - /// The ID of the that should be canceled. + /// The ID of the that should be canceled. /// /// A token that can be used to cancel this method call. /// An updated instance. @@ -769,7 +757,7 @@ public virtual ClientResult CancelBatchFileJob(string v ClientResult result = CancelBatchFileJob(vectorStoreId, batchJobId, cancellationToken.ToRequestOptions()); PipelineResponse response = result?.GetRawResponse(); - VectorStoreBatchFileJob value = VectorStoreBatchFileJob.FromResponse(response); + VectorStoreBatchFileJob value = (VectorStoreBatchFileJob)result; return ClientResult.FromValue(value, response); } } diff --git a/src/Custom/VectorStores/VectorStoreCollectionOrder.cs b/src/Custom/VectorStores/VectorStoreCollectionOrder.cs index d6f294c96..89aa5eda2 100644 --- a/src/Custom/VectorStores/VectorStoreCollectionOrder.cs +++ b/src/Custom/VectorStores/VectorStoreCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct VectorStoreCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static VectorStoreCollectionOrder Ascending { get; } = new VectorStoreCollectionOrder(AscendingValue); + public static VectorStoreCollectionOrder Ascending { get; } = new VectorStoreCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static VectorStoreCollectionOrder Descending { get; } = new VectorStoreCollectionOrder(DescendingValue); + public static VectorStoreCollectionOrder Descending { get; } = new VectorStoreCollectionOrder(DescValue); } diff --git a/src/Custom/VectorStores/VectorStoreExpirationPolicy.cs b/src/Custom/VectorStores/VectorStoreExpirationPolicy.cs index 8b437809f..bf8bb7907 100644 --- a/src/Custom/VectorStores/VectorStoreExpirationPolicy.cs +++ b/src/Custom/VectorStores/VectorStoreExpirationPolicy.cs @@ -14,8 +14,6 @@ namespace OpenAI.VectorStores; [CodeGenSuppress(nameof(VectorStoreExpirationPolicy), typeof(VectorStoreExpirationAnchor), typeof(int), typeof(IDictionary))] public partial class VectorStoreExpirationPolicy { - private IDictionary SerializedAdditionalRawData; - [CodeGenMember("Anchor")] private VectorStoreExpirationAnchor _anchor; [CodeGenMember("Days")] diff --git a/src/Custom/VectorStores/VectorStoreFileAssociationCollectionOrder.cs b/src/Custom/VectorStores/VectorStoreFileAssociationCollectionOrder.cs index 888cf8322..a71f40fa3 100644 --- a/src/Custom/VectorStores/VectorStoreFileAssociationCollectionOrder.cs +++ b/src/Custom/VectorStores/VectorStoreFileAssociationCollectionOrder.cs @@ -9,9 +9,9 @@ public readonly partial struct VectorStoreFileAssociationCollectionOrder { // CUSTOM: Renamed. [CodeGenMember("Asc")] - public static VectorStoreFileAssociationCollectionOrder Ascending { get; } = new VectorStoreFileAssociationCollectionOrder(AscendingValue); + public static VectorStoreFileAssociationCollectionOrder Ascending { get; } = new VectorStoreFileAssociationCollectionOrder(AscValue); // CUSTOM: Renamed. [CodeGenMember("Desc")] - public static VectorStoreFileAssociationCollectionOrder Descending { get; } = new VectorStoreFileAssociationCollectionOrder(DescendingValue); + public static VectorStoreFileAssociationCollectionOrder Descending { get; } = new VectorStoreFileAssociationCollectionOrder(DescValue); } diff --git a/src/Generated/AssistantClient.RestClient.cs b/src/Generated/AssistantClient.RestClient.cs new file mode 100644 index 000000000..aceab6704 --- /dev/null +++ b/src/Generated/AssistantClient.RestClient.cs @@ -0,0 +1,115 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Assistants +{ + public partial class AssistantClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateAssistantRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/assistants", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListAssistantsRequest(int? limit, string order, string after, string before, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/assistants", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateGetAssistantRequest(string assistantId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/assistants/", false); + uri.AppendPath(assistantId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateModifyAssistantRequest(string assistantId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/assistants/", false); + uri.AppendPath(assistantId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDeleteAssistantRequest(string assistantId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "DELETE"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/assistants/", false); + uri.AppendPath(assistantId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/AssistantClient.cs b/src/Generated/AssistantClient.cs index 34fb05f58..8af7745ec 100644 --- a/src/Generated/AssistantClient.cs +++ b/src/Generated/AssistantClient.cs @@ -5,122 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Assistants { - // Data plane generated sub-client. public partial class AssistantClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected AssistantClient() { } - internal PipelineMessage CreateCreateAssistantRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/assistants", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetAssistantsRequest(int? limit, string order, string after, string before, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/assistants", false); - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - if (order != null) - { - uri.AppendQuery("order", order, true); - } - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (before != null) - { - uri.AppendQuery("before", before, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetAssistantRequest(string assistantId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/assistants/", false); - uri.AppendPath(assistantId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateModifyAssistantRequest(string assistantId, BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/assistants/", false); - uri.AppendPath(assistantId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDeleteAssistantRequest(string assistantId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "DELETE"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/assistants/", false); - uri.AppendPath(assistantId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/AudioClient.RestClient.cs b/src/Generated/AudioClient.RestClient.cs new file mode 100644 index 000000000..32414e385 --- /dev/null +++ b/src/Generated/AudioClient.RestClient.cs @@ -0,0 +1,68 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Audio +{ + public partial class AudioClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateSpeechRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/audio/speech", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/octet-stream"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCreateTranscriptionRequest(BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/audio/transcriptions", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCreateTranslationRequest(BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/audio/translations", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/AudioClient.cs b/src/Generated/AudioClient.cs index 285c3ffd3..1815a1756 100644 --- a/src/Generated/AudioClient.cs +++ b/src/Generated/AudioClient.cs @@ -5,75 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Audio { - // Data plane generated sub-client. public partial class AudioClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected AudioClient() { } - internal PipelineMessage CreateCreateSpeechRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/audio/speech", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/octet-stream"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateCreateTranscriptionRequest(BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/audio/transcriptions", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateCreateTranslationRequest(BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/audio/translations", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/BatchClient.RestClient.cs b/src/Generated/BatchClient.RestClient.cs new file mode 100644 index 000000000..5e7c89126 --- /dev/null +++ b/src/Generated/BatchClient.RestClient.cs @@ -0,0 +1,39 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Batch +{ + public partial class BatchClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateListBatchesRequest(string after, int? limit, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/batches", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/BatchClient.cs b/src/Generated/BatchClient.cs index ab9059d81..48df1fec3 100644 --- a/src/Generated/BatchClient.cs +++ b/src/Generated/BatchClient.cs @@ -5,25 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading.Tasks; namespace OpenAI.Batch { - // Data plane generated sub-client. public partial class BatchClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected BatchClient() { } - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/ChatClient.RestClient.cs b/src/Generated/ChatClient.RestClient.cs new file mode 100644 index 000000000..2b61a84e4 --- /dev/null +++ b/src/Generated/ChatClient.RestClient.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Chat +{ + public partial class ChatClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateChatCompletionRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/chat/completions", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/ChatClient.cs b/src/Generated/ChatClient.cs index 32af72c93..1812c542a 100644 --- a/src/Generated/ChatClient.cs +++ b/src/Generated/ChatClient.cs @@ -5,41 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Chat { - // Data plane generated sub-client. public partial class ChatClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected ChatClient() { } - internal PipelineMessage CreateCreateChatCompletionRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/chat/completions", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/EmbeddingClient.RestClient.cs b/src/Generated/EmbeddingClient.RestClient.cs new file mode 100644 index 000000000..5854624b1 --- /dev/null +++ b/src/Generated/EmbeddingClient.RestClient.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Embeddings +{ + public partial class EmbeddingClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateEmbeddingRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/embeddings", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/EmbeddingClient.cs b/src/Generated/EmbeddingClient.cs index 6f7f1c81c..2e81fb221 100644 --- a/src/Generated/EmbeddingClient.cs +++ b/src/Generated/EmbeddingClient.cs @@ -5,41 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Embeddings { - // Data plane generated sub-client. public partial class EmbeddingClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected EmbeddingClient() { } - internal PipelineMessage CreateCreateEmbeddingRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/embeddings", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/FineTuningClient.RestClient.cs b/src/Generated/FineTuningClient.RestClient.cs new file mode 100644 index 000000000..190bee083 --- /dev/null +++ b/src/Generated/FineTuningClient.RestClient.cs @@ -0,0 +1,106 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.FineTuning +{ + public partial class FineTuningClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateListPaginatedFineTuningJobsRequest(string after, int? limit, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/fine_tuning/jobs", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCancelFineTuningJobRequest(string fineTuningJobId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/fine_tuning/jobs/", false); + uri.AppendPath(fineTuningJobId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListFineTuningJobCheckpointsRequest(string fineTuningJobId, string after, int? limit, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/fine_tuning/jobs/", false); + uri.AppendPath(fineTuningJobId, true); + uri.AppendPath("/checkpoints", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListFineTuningEventsRequest(string fineTuningJobId, string after, int? limit, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/fine_tuning/jobs/", false); + uri.AppendPath(fineTuningJobId, true); + uri.AppendPath("/events", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/FineTuningClient.cs b/src/Generated/FineTuningClient.cs index 5f7d520c1..d7df5cd35 100644 --- a/src/Generated/FineTuningClient.cs +++ b/src/Generated/FineTuningClient.cs @@ -5,91 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.FineTuning { - // Data plane generated sub-client. public partial class FineTuningClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected FineTuningClient() { } - internal PipelineMessage CreateCancelFineTuningJobRequest(string fineTuningJobId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/fine_tuning/jobs/", false); - uri.AppendPath(fineTuningJobId, true); - uri.AppendPath("/cancel", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetFineTuningJobCheckpointsRequest(string fineTuningJobId, string after, int? limit, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/fine_tuning/jobs/", false); - uri.AppendPath(fineTuningJobId, true); - uri.AppendPath("/checkpoints", false); - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetFineTuningEventsRequest(string fineTuningJobId, string after, int? limit, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/fine_tuning/jobs/", false); - uri.AppendPath(fineTuningJobId, true); - uri.AppendPath("/events", false); - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/ImageClient.RestClient.cs b/src/Generated/ImageClient.RestClient.cs new file mode 100644 index 000000000..7118e55c4 --- /dev/null +++ b/src/Generated/ImageClient.RestClient.cs @@ -0,0 +1,68 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Images +{ + public partial class ImageClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateImageRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/images/generations", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCreateImageEditRequest(BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/images/edits", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCreateImageVariationRequest(BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/images/variations", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/ImageClient.cs b/src/Generated/ImageClient.cs index a92809a82..baaaa6c0e 100644 --- a/src/Generated/ImageClient.cs +++ b/src/Generated/ImageClient.cs @@ -5,75 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Images { - // Data plane generated sub-client. public partial class ImageClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected ImageClient() { } - internal PipelineMessage CreateCreateImageRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/images/generations", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateCreateImageEditRequest(BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/images/edits", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateCreateImageVariationRequest(BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/images/variations", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/Internal/Argument.cs b/src/Generated/Internal/Argument.cs index 29cb5ac18..6e8945dda 100644 --- a/src/Generated/Internal/Argument.cs +++ b/src/Generated/Internal/Argument.cs @@ -8,7 +8,7 @@ namespace OpenAI { - internal static class Argument + internal static partial class Argument { public static void AssertNotNull(T value, string name) { @@ -19,7 +19,7 @@ public static void AssertNotNull(T value, string name) } public static void AssertNotNull(T? value, string name) - where T : struct + where T : struct { if (!value.HasValue) { @@ -73,7 +73,7 @@ public static void AssertNotNullOrWhiteSpace(string value, string name) } public static void AssertNotDefault(ref T value, string name) - where T : struct, IEquatable + where T : struct, IEquatable { if (value.Equals(default)) { @@ -82,7 +82,7 @@ public static void AssertNotDefault(ref T value, string name) } public static void AssertInRange(T value, T minimum, T maximum, string name) - where T : notnull, IComparable + where T : notnull, IComparable { if (minimum.CompareTo(value) > 0) { @@ -103,7 +103,7 @@ public static void AssertEnumDefined(Type enumType, object value, string name) } public static T CheckNotNull(T value, string name) - where T : class + where T : class { AssertNotNull(value, name); return value; diff --git a/src/Generated/Internal/BinaryContentHelper.cs b/src/Generated/Internal/BinaryContentHelper.cs index 52bcdbdf3..a3f8eae20 100644 --- a/src/Generated/Internal/BinaryContentHelper.cs +++ b/src/Generated/Internal/BinaryContentHelper.cs @@ -9,10 +9,10 @@ namespace OpenAI { - internal static class BinaryContentHelper + internal static partial class BinaryContentHelper { public static BinaryContent FromEnumerable(IEnumerable enumerable) - where T : notnull + where T : notnull { Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); content.JsonWriter.WriteStartArray(); @@ -38,7 +38,7 @@ public static BinaryContent FromEnumerable(IEnumerable enumerable) else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); + content.JsonWriter.WriteRawValue(item); #else using (JsonDocument document = JsonDocument.Parse(item)) { @@ -53,11 +53,12 @@ public static BinaryContent FromEnumerable(IEnumerable enumerable) } public static BinaryContent FromEnumerable(ReadOnlySpan span) - where T : notnull + where T : notnull { Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); content.JsonWriter.WriteStartArray(); - for (int i = 0; i < span.Length; i++) + int i = 0; + for (; i < span.Length; i++) { content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); } @@ -67,7 +68,7 @@ public static BinaryContent FromEnumerable(ReadOnlySpan span) } public static BinaryContent FromDictionary(IDictionary dictionary) - where TValue : notnull + where TValue : notnull { Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); content.JsonWriter.WriteStartObject(); @@ -95,7 +96,7 @@ public static BinaryContent FromDictionary(IDictionary dicti else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); + content.JsonWriter.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -120,7 +121,7 @@ public static BinaryContent FromObject(BinaryData value) { Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(value); + content.JsonWriter.WriteRawValue(value); #else using (JsonDocument document = JsonDocument.Parse(value)) { diff --git a/src/Generated/Internal/ChangeTrackingDictionary.cs b/src/Generated/Internal/ChangeTrackingDictionary.cs index 2eb05d04a..5502b8660 100644 --- a/src/Generated/Internal/ChangeTrackingDictionary.cs +++ b/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -8,7 +8,8 @@ namespace OpenAI { - internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + internal partial class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary + where TKey : notnull { private IDictionary _innerDictionary; diff --git a/src/Generated/Internal/ChangeTrackingList.cs b/src/Generated/Internal/ChangeTrackingList.cs index c64afc504..641f91d99 100644 --- a/src/Generated/Internal/ChangeTrackingList.cs +++ b/src/Generated/Internal/ChangeTrackingList.cs @@ -9,7 +9,7 @@ namespace OpenAI { - internal class ChangeTrackingList : IList, IReadOnlyList + internal partial class ChangeTrackingList : IList, IReadOnlyList { private IList _innerList; diff --git a/src/Generated/Internal/ClientUriBuilder.cs b/src/Generated/Internal/ClientUriBuilder.cs index 9406854da..066512b50 100644 --- a/src/Generated/Internal/ClientUriBuilder.cs +++ b/src/Generated/Internal/ClientUriBuilder.cs @@ -9,7 +9,7 @@ namespace OpenAI { - internal class ClientUriBuilder + internal partial class ClientUriBuilder { private UriBuilder _uriBuilder; private StringBuilder _pathBuilder; @@ -19,11 +19,11 @@ public ClientUriBuilder() { } - private UriBuilder UriBuilder => _uriBuilder ??= new UriBuilder(); + private UriBuilder UriBuilder => _uriBuilder ??= new UriBuilder(); - private StringBuilder PathBuilder => _pathBuilder ??= new StringBuilder(UriBuilder.Path); + private StringBuilder PathBuilder => _pathBuilder ??= new StringBuilder(UriBuilder.Path); - private StringBuilder QueryBuilder => _queryBuilder ??= new StringBuilder(UriBuilder.Query); + private StringBuilder QueryBuilder => _queryBuilder ??= new StringBuilder(UriBuilder.Query); public void Reset(Uri uri) { @@ -34,156 +34,84 @@ public void Reset(Uri uri) public void AppendPath(string value, bool escape) { - Argument.AssertNotNullOrWhiteSpace(value, nameof(value)); - if (escape) { value = Uri.EscapeDataString(value); } - if (PathBuilder.Length > 0 && PathBuilder[PathBuilder.Length - 1] == '/' && value[0] == '/') { PathBuilder.Remove(PathBuilder.Length - 1, 1); } - PathBuilder.Append(value); UriBuilder.Path = PathBuilder.ToString(); } - public void AppendPath(bool value, bool escape = false) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(bool value, bool escape = false) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(float value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(float value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(double value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(double value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(int value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(int value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(byte[] value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendPath(byte[] value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - public void AppendPath(IEnumerable value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(DateTimeOffset value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - public void AppendPath(DateTimeOffset value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendPath(TimeSpan value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - public void AppendPath(TimeSpan value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendPath(Guid value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(Guid value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendPath(long value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - public void AppendPath(long value, bool escape = true) + public void AppendPathDelimited(IEnumerable value, string delimiter, string format = null, bool escape = true) { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); + delimiter ??= ","; + IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); + AppendPath(string.Join(delimiter, stringValues), escape); } public void AppendQuery(string name, string value, bool escape) { - Argument.AssertNotNullOrWhiteSpace(name, nameof(name)); - Argument.AssertNotNullOrWhiteSpace(value, nameof(value)); - if (QueryBuilder.Length > 0) { QueryBuilder.Append('&'); } - if (escape) { value = Uri.EscapeDataString(value); } - QueryBuilder.Append(name); QueryBuilder.Append('='); QueryBuilder.Append(value); } - public void AppendQuery(string name, bool value, bool escape = false) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, float value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, bool value, bool escape = false) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendQuery(string name, float value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - public void AppendQuery(string name, double value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - public void AppendQuery(string name, decimal value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, double value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, int value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, decimal value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, long value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, int value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, TimeSpan value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, long value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, byte[] value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } + public void AppendQuery(string name, TimeSpan value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQuery(string name, Guid value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } + public void AppendQuery(string name, byte[] value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, bool escape = true) - { - var stringValues = value.Select(v => ModelSerializationExtensions.TypeFormatters.ConvertToString(v)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } + public void AppendQuery(string name, Guid value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string format, bool escape = true) + public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string format = null, bool escape = true) { - var stringValues = value.Select(v => ModelSerializationExtensions.TypeFormatters.ConvertToString(v, format)); + delimiter ??= ","; + IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); AppendQuery(name, string.Join(delimiter, stringValues), escape); } @@ -193,12 +121,10 @@ public Uri ToUri() { UriBuilder.Path = _pathBuilder.ToString(); } - if (_queryBuilder != null) { UriBuilder.Query = _queryBuilder.ToString(); } - return UriBuilder.Uri; } } diff --git a/src/Generated/Internal/ErrorResult.cs b/src/Generated/Internal/ErrorResult.cs index 42938626f..745190d34 100644 --- a/src/Generated/Internal/ErrorResult.cs +++ b/src/Generated/Internal/ErrorResult.cs @@ -7,7 +7,7 @@ namespace OpenAI { - internal class ErrorResult : ClientResult + internal partial class ErrorResult : ClientResult { private readonly PipelineResponse _response; private readonly ClientResultException _exception; diff --git a/src/Generated/Internal/ModelSerializationExtensions.cs b/src/Generated/Internal/ModelSerializationExtensions.cs index d1334d37b..50a860ac2 100644 --- a/src/Generated/Internal/ModelSerializationExtensions.cs +++ b/src/Generated/Internal/ModelSerializationExtensions.cs @@ -8,14 +8,13 @@ using System.Diagnostics; using System.Globalization; using System.Text.Json; -using System.Xml; namespace OpenAI { - internal static class ModelSerializationExtensions + internal static partial class ModelSerializationExtensions { internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - internal static readonly BinaryData SentinelValue = BinaryData.FromObjectAsJson("__EMPTY__"); + private static readonly BinaryData _sentinelValue = BinaryData.FromBytes("\"__EMPTY__\""u8.ToArray()); public static object GetObject(this JsonElement element) { @@ -41,14 +40,14 @@ public static object GetObject(this JsonElement element) case JsonValueKind.Null: return null; case JsonValueKind.Object: - var dictionary = new Dictionary(); + Dictionary dictionary = new Dictionary(); foreach (var jsonProperty in element.EnumerateObject()) { dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); } return dictionary; case JsonValueKind.Array: - var list = new List(); + List list = new List(); foreach (var item in element.EnumerateArray()) { list.Add(item.GetObject()); @@ -86,7 +85,7 @@ public static char GetChar(this JsonElement element) { if (element.ValueKind == JsonValueKind.String) { - var text = element.GetString(); + string text = element.GetString(); if (text == null || text.Length != 1) { throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); @@ -100,14 +99,14 @@ public static char GetChar(this JsonElement element) } [Conditional("DEBUG")] - public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + public static void ThrowNonNullablePropertyIsNull(this JsonProperty @property) { - throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + throw new JsonException($"A property '{@property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); } public static string GetRequiredString(this JsonElement element) { - var value = element.GetString(); + string value = element.GetString(); if (value == null) { throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); @@ -252,148 +251,9 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, object value, Mo internal static bool IsSentinelValue(BinaryData value) { - ReadOnlySpan sentinelSpan = SentinelValue.ToMemory().Span; + ReadOnlySpan sentinelSpan = _sentinelValue.ToMemory().Span; ReadOnlySpan valueSpan = value.ToMemory().Span; return sentinelSpan.SequenceEqual(valueSpan); } - - internal static class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public const string DefaultNumberFormat = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Generated clients require it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; - int size = checked(numWholeOrPartialInputBlocks * 4); - char[] output = new char[size]; - - int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - int i = 0; - for (; i < numBase64Chars; i++) - { - char ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else - { - if (ch == '/') - { - output[i] = '_'; - } - else - { - if (ch == '=') - { - break; - } - } - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - int paddingCharsToAdd = (value.Length % 4) switch - { - 0 => 0, - 2 => 2, - 3 => 1, - _ => throw new InvalidOperationException("Malformed input") - }; - char[] output = new char[(value.Length + paddingCharsToAdd)]; - int i = 0; - for (; i < value.Length; i++) - { - char ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else - { - if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object value, string format = null) => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b0 when format != null => ToString(b0, format), - IEnumerable s0 => string.Join(",", s0), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), - Guid guid => guid.ToString(), - BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), - _ => value.ToString() - }; - } } } diff --git a/src/Generated/Internal/Optional.cs b/src/Generated/Internal/Optional.cs index 7b3fe4806..e4ae0dc30 100644 --- a/src/Generated/Internal/Optional.cs +++ b/src/Generated/Internal/Optional.cs @@ -7,7 +7,7 @@ namespace OpenAI { - internal static class Optional + internal static partial class Optional { public static bool IsCollectionDefined(IEnumerable collection) { @@ -25,7 +25,7 @@ public static bool IsCollectionDefined(IReadOnlyDictionary(T? value) - where T : struct + where T : struct { return value.HasValue; } @@ -35,14 +35,14 @@ public static bool IsDefined(object value) return value != null; } - public static bool IsDefined(JsonElement value) + public static bool IsDefined(string value) { - return value.ValueKind != JsonValueKind.Undefined; + return value != null; } - public static bool IsDefined(string value) + public static bool IsDefined(JsonElement value) { - return value != null; + return value.ValueKind != JsonValueKind.Undefined; } } } diff --git a/src/Generated/Internal/PipelineRequestHeadersExtensions.cs b/src/Generated/Internal/PipelineRequestHeadersExtensions.cs new file mode 100644 index 000000000..e1849facc --- /dev/null +++ b/src/Generated/Internal/PipelineRequestHeadersExtensions.cs @@ -0,0 +1,25 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Linq; + +namespace OpenAI +{ + internal static partial class PipelineRequestHeadersExtensions + { + public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter) + { + IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v)); + headers.Set(name, string.Join(delimiter, stringValues)); + } + + public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter, string format) + { + IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); + headers.Set(name, string.Join(delimiter, stringValues)); + } + } +} diff --git a/src/Generated/Internal/TypeFormatters.cs b/src/Generated/Internal/TypeFormatters.cs new file mode 100644 index 000000000..e21a80fff --- /dev/null +++ b/src/Generated/Internal/TypeFormatters.cs @@ -0,0 +1,150 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Xml; + +namespace OpenAI +{ + internal static partial class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Generated clients require it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => System.Xml.XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked (value.Length + 2) / 3; + int size = checked (numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => System.Xml.XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => System.Xml.XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } +} diff --git a/src/Generated/Internal/Utf8JsonBinaryContent.cs b/src/Generated/Internal/Utf8JsonBinaryContent.cs index 1f7d30685..bcf766a67 100644 --- a/src/Generated/Internal/Utf8JsonBinaryContent.cs +++ b/src/Generated/Internal/Utf8JsonBinaryContent.cs @@ -10,7 +10,7 @@ namespace OpenAI { - internal class Utf8JsonBinaryContent : BinaryContent + internal partial class Utf8JsonBinaryContent : BinaryContent { private readonly MemoryStream _stream; private readonly BinaryContent _content; diff --git a/src/Generated/InternalAssistantMessageClient.RestClient.cs b/src/Generated/InternalAssistantMessageClient.RestClient.cs new file mode 100644 index 000000000..ee4043f1a --- /dev/null +++ b/src/Generated/InternalAssistantMessageClient.RestClient.cs @@ -0,0 +1,125 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantMessageClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateMessageRequest(string threadId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListMessagesRequest(string threadId, int? limit, string order, string after, string before, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateGetMessageRequest(string threadId, string messageId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages/", false); + uri.AppendPath(messageId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateModifyMessageRequest(string threadId, string messageId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages/", false); + uri.AppendPath(messageId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDeleteMessageRequest(string threadId, string messageId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "DELETE"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages/", false); + uri.AppendPath(messageId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/InternalAssistantMessageClient.cs b/src/Generated/InternalAssistantMessageClient.cs index daee4b083..803c34566 100644 --- a/src/Generated/InternalAssistantMessageClient.cs +++ b/src/Generated/InternalAssistantMessageClient.cs @@ -6,147 +6,37 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Threading.Tasks; +using OpenAI; namespace OpenAI.Assistants { - // Data plane generated sub-client. internal partial class InternalAssistantMessageClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected InternalAssistantMessageClient() { } - public virtual async Task GetMessagesAsync(string threadId, int? limit, string order, string after, string before, RequestOptions options) - { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using PipelineMessage message = CreateGetMessagesRequest(threadId, limit, order, after, before, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); - } + public ClientPipeline Pipeline { get; } - public virtual ClientResult GetMessages(string threadId, int? limit, string order, string after, string before, RequestOptions options) + public virtual ClientResult ListMessages(string threadId, int? limit = null, string order = null, string after = null, string before = null, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(threadId, nameof(threadId)); - using PipelineMessage message = CreateGetMessagesRequest(threadId, limit, order, after, before, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = CreateListMessagesRequest(threadId, limit, order, after, before, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - internal PipelineMessage CreateCreateMessageRequest(string threadId, BinaryContent content, RequestOptions options) + public virtual async Task ListMessagesAsync(string threadId, int? limit = null, string order = null, string after = null, string before = null, RequestOptions options = null) { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/messages", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } + Argument.AssertNotNull(threadId, nameof(threadId)); - internal PipelineMessage CreateGetMessagesRequest(string threadId, int? limit, string order, string after, string before, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/messages", false); - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - if (order != null) - { - uri.AppendQuery("order", order, true); - } - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (before != null) - { - uri.AppendQuery("before", before, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; + using PipelineMessage message = CreateListMessagesRequest(threadId, limit, order, after, before, options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - - internal PipelineMessage CreateGetMessageRequest(string threadId, string messageId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/messages/", false); - uri.AppendPath(messageId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateModifyMessageRequest(string threadId, string messageId, BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/messages/", false); - uri.AppendPath(messageId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDeleteMessageRequest(string threadId, string messageId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "DELETE"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/messages/", false); - uri.AppendPath(messageId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); } } diff --git a/src/Generated/InternalAssistantRunClient.RestClient.cs b/src/Generated/InternalAssistantRunClient.RestClient.cs new file mode 100644 index 000000000..d0e3a535a --- /dev/null +++ b/src/Generated/InternalAssistantRunClient.RestClient.cs @@ -0,0 +1,232 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using OpenAI; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantRunClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateThreadAndRunRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/runs", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCreateRunRequest(string threadId, BinaryContent content, IEnumerable include, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs", false); + if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", include, ",", null, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListRunsRequest(string threadId, int? limit, string order, string after, string before, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateGetRunRequest(string threadId, string runId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateModifyRunRequest(string threadId, string runId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCancelRunRequest(string threadId, string runId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateSubmitToolOutputsToRunRequest(string threadId, string runId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/submit_tool_outputs", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListRunStepsRequest(string threadId, string runId, int? limit, string order, string after, string before, IEnumerable include, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/steps", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", include, ",", null, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateGetRunStepRequest(string threadId, string runId, string stepId, IEnumerable include, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/steps/", false); + uri.AppendPath(stepId, true); + if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", include, ",", null, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/InternalAssistantRunClient.cs b/src/Generated/InternalAssistantRunClient.cs index 1c80d9819..84636685d 100644 --- a/src/Generated/InternalAssistantRunClient.cs +++ b/src/Generated/InternalAssistantRunClient.cs @@ -5,255 +5,38 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; using System.Threading.Tasks; +using OpenAI; namespace OpenAI.Assistants { - // Data plane generated sub-client. internal partial class InternalAssistantRunClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected InternalAssistantRunClient() { } - public virtual async Task GetRunsAsync(string threadId, int? limit, string order, string after, string before, RequestOptions options) - { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using PipelineMessage message = CreateGetRunsRequest(threadId, limit, order, after, before, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); - } + public ClientPipeline Pipeline { get; } - public virtual ClientResult GetRuns(string threadId, int? limit, string order, string after, string before, RequestOptions options) + public virtual ClientResult ListRuns(string threadId, int? limit = null, string order = null, string after = null, string before = null, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(threadId, nameof(threadId)); - using PipelineMessage message = CreateGetRunsRequest(threadId, limit, order, after, before, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = CreateListRunsRequest(threadId, limit, order, after, before, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - internal PipelineMessage CreateCreateThreadAndRunRequest(BinaryContent content, RequestOptions options) + public virtual async Task ListRunsAsync(string threadId, int? limit = null, string order = null, string after = null, string before = null, RequestOptions options = null) { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/runs", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } + Argument.AssertNotNull(threadId, nameof(threadId)); - internal PipelineMessage CreateCreateRunRequest(string threadId, BinaryContent content, IEnumerable include, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs", false); - if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) - { - uri.AppendQueryDelimited("include[]", include, ",", true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; + using PipelineMessage message = CreateListRunsRequest(threadId, limit, order, after, before, options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - - internal PipelineMessage CreateGetRunsRequest(string threadId, int? limit, string order, string after, string before, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs", false); - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - if (order != null) - { - uri.AppendQuery("order", order, true); - } - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (before != null) - { - uri.AppendQuery("before", before, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetRunRequest(string threadId, string runId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateModifyRunRequest(string threadId, string runId, BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateCancelRunRequest(string threadId, string runId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - uri.AppendPath("/cancel", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateSubmitToolOutputsToRunRequest(string threadId, string runId, BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - uri.AppendPath("/submit_tool_outputs", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetRunStepsRequest(string threadId, string runId, int? limit, string order, string after, string before, IEnumerable include, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - uri.AppendPath("/steps", false); - if (limit != null) - { - uri.AppendQuery("limit", limit.Value, true); - } - if (order != null) - { - uri.AppendQuery("order", order, true); - } - if (after != null) - { - uri.AppendQuery("after", after, true); - } - if (before != null) - { - uri.AppendQuery("before", before, true); - } - if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) - { - uri.AppendQueryDelimited("include[]", include, ",", true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetRunStepRequest(string threadId, string runId, string stepId, IEnumerable include, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - uri.AppendPath("/runs/", false); - uri.AppendPath(runId, true); - uri.AppendPath("/steps/", false); - uri.AppendPath(stepId, true); - if (include != null && !(include is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) - { - uri.AppendQueryDelimited("include[]", include, ",", true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); } } diff --git a/src/Generated/InternalAssistantThreadClient.RestClient.cs b/src/Generated/InternalAssistantThreadClient.RestClient.cs new file mode 100644 index 000000000..1064c666e --- /dev/null +++ b/src/Generated/InternalAssistantThreadClient.RestClient.cs @@ -0,0 +1,84 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Assistants +{ + internal partial class InternalAssistantThreadClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateThreadRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateGetThreadRequest(string threadId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateModifyThreadRequest(string threadId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDeleteThreadRequest(string threadId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "DELETE"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/InternalAssistantThreadClient.cs b/src/Generated/InternalAssistantThreadClient.cs index 8c7c5d69d..6981b71d5 100644 --- a/src/Generated/InternalAssistantThreadClient.cs +++ b/src/Generated/InternalAssistantThreadClient.cs @@ -5,91 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Assistants { - // Data plane generated sub-client. internal partial class InternalAssistantThreadClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected InternalAssistantThreadClient() { } - internal PipelineMessage CreateCreateThreadRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetThreadRequest(string threadId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateModifyThreadRequest(string threadId, BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDeleteThreadRequest(string threadId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "DELETE"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/threads/", false); - uri.AppendPath(threadId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/InternalUploadsClient.RestClient.cs b/src/Generated/InternalUploadsClient.RestClient.cs new file mode 100644 index 000000000..e107394fd --- /dev/null +++ b/src/Generated/InternalUploadsClient.RestClient.cs @@ -0,0 +1,89 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Files +{ + internal partial class InternalUploadsClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateUploadRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateAddUploadPartRequest(string uploadId, BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/parts", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCompleteUploadRequest(string uploadId, BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/complete", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateCancelUploadRequest(string uploadId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/InternalUploadsClient.cs b/src/Generated/InternalUploadsClient.cs index afa20147c..79a2890df 100644 --- a/src/Generated/InternalUploadsClient.cs +++ b/src/Generated/InternalUploadsClient.cs @@ -5,238 +5,141 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; +using System.Threading; using System.Threading.Tasks; +using OpenAI; namespace OpenAI.Files { - // Data plane generated sub-client. internal partial class InternalUploadsClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected InternalUploadsClient() { } - public virtual async Task> CreateUploadAsync(InternalCreateUploadRequest requestBody) - { - Argument.AssertNotNull(requestBody, nameof(requestBody)); - - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = await CreateUploadAsync(content, null).ConfigureAwait(false); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); - } - - public virtual ClientResult CreateUpload(InternalCreateUploadRequest requestBody) - { - Argument.AssertNotNull(requestBody, nameof(requestBody)); - - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = CreateUpload(content, null); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); - } + public ClientPipeline Pipeline { get; } - public virtual async Task CreateUploadAsync(BinaryContent content, RequestOptions options = null) + public virtual ClientResult CreateUpload(BinaryContent content, RequestOptions options = null) { Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateUploadRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - public virtual ClientResult CreateUpload(BinaryContent content, RequestOptions options = null) + public virtual async Task CreateUploadAsync(BinaryContent content, RequestOptions options = null) { Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateUploadRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - public virtual async Task> AddUploadPartAsync(string uploadId, InternalAddUploadPartRequest requestBody) + public virtual ClientResult CreateUpload(InternalCreateUploadRequest requestBody, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); Argument.AssertNotNull(requestBody, nameof(requestBody)); - using MultipartFormDataBinaryContent content = requestBody.ToMultipartBinaryBody(); - ClientResult result = await AddUploadPartAsync(uploadId, content, content.ContentType, (RequestOptions)null).ConfigureAwait(false); - return ClientResult.FromValue(InternalUploadPart.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + ClientResult result = CreateUpload(requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - public virtual ClientResult AddUploadPart(string uploadId, InternalAddUploadPartRequest requestBody) + public virtual async Task> CreateUploadAsync(InternalCreateUploadRequest requestBody, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); Argument.AssertNotNull(requestBody, nameof(requestBody)); - using MultipartFormDataBinaryContent content = requestBody.ToMultipartBinaryBody(); - ClientResult result = AddUploadPart(uploadId, content, content.ContentType, (RequestOptions)null); - return ClientResult.FromValue(InternalUploadPart.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + ClientResult result = await CreateUploadAsync(requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null).ConfigureAwait(false); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - public virtual async Task AddUploadPartAsync(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) + public virtual ClientResult AddUploadPart(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - public virtual ClientResult AddUploadPart(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) + public virtual async Task AddUploadPartAsync(string uploadId, BinaryContent content, string contentType, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); - } - - public virtual async Task> CompleteUploadAsync(string uploadId, InternalCompleteUploadRequest requestBody) - { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); - Argument.AssertNotNull(requestBody, nameof(requestBody)); - - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = await CompleteUploadAsync(uploadId, content, null).ConfigureAwait(false); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - public virtual ClientResult CompleteUpload(string uploadId, InternalCompleteUploadRequest requestBody) - { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); - Argument.AssertNotNull(requestBody, nameof(requestBody)); - - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = CompleteUpload(uploadId, content, null); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); - } - - public virtual async Task CompleteUploadAsync(string uploadId, BinaryContent content, RequestOptions options = null) + public virtual ClientResult CompleteUpload(string uploadId, BinaryContent content, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCompleteUploadRequest(uploadId, content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - public virtual ClientResult CompleteUpload(string uploadId, BinaryContent content, RequestOptions options = null) + public virtual async Task CompleteUploadAsync(string uploadId, BinaryContent content, RequestOptions options = null) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCompleteUploadRequest(uploadId, content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - public virtual async Task> CancelUploadAsync(string uploadId) + public virtual ClientResult CompleteUpload(string uploadId, InternalCompleteUploadRequest requestBody, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); - ClientResult result = await CancelUploadAsync(uploadId, null).ConfigureAwait(false); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + ClientResult result = CompleteUpload(uploadId, requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - public virtual ClientResult CancelUpload(string uploadId) + public virtual async Task> CompleteUploadAsync(string uploadId, InternalCompleteUploadRequest requestBody, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); - ClientResult result = CancelUpload(uploadId, null); - return ClientResult.FromValue(InternalUpload.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + ClientResult result = await CompleteUploadAsync(uploadId, requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null).ConfigureAwait(false); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - public virtual async Task CancelUploadAsync(string uploadId, RequestOptions options) + public virtual ClientResult CancelUpload(string uploadId, RequestOptions options) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); using PipelineMessage message = CreateCancelUploadRequest(uploadId, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - public virtual ClientResult CancelUpload(string uploadId, RequestOptions options) + public virtual async Task CancelUploadAsync(string uploadId, RequestOptions options) { - Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); using PipelineMessage message = CreateCancelUploadRequest(uploadId, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - internal PipelineMessage CreateCreateUploadRequest(BinaryContent content, RequestOptions options) + public virtual ClientResult CancelUpload(string uploadId, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/uploads", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } + Argument.AssertNotNull(uploadId, nameof(uploadId)); - internal PipelineMessage CreateAddUploadPartRequest(string uploadId, BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/uploads/", false); - uri.AppendPath(uploadId, true); - uri.AppendPath("/parts", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; + ClientResult result = CancelUpload(uploadId, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - internal PipelineMessage CreateCompleteUploadRequest(string uploadId, BinaryContent content, RequestOptions options) + public virtual async Task> CancelUploadAsync(string uploadId, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/uploads/", false); - uri.AppendPath(uploadId, true); - uri.AppendPath("/complete", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } + Argument.AssertNotNull(uploadId, nameof(uploadId)); - internal PipelineMessage CreateCancelUploadRequest(string uploadId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/uploads/", false); - uri.AppendPath(uploadId, true); - uri.AppendPath("/cancel", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; + ClientResult result = await CancelUploadAsync(uploadId, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null).ConfigureAwait(false); + return ClientResult.FromValue((InternalUpload)result, result.GetRawResponse()); } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); } } diff --git a/src/Generated/LegacyCompletionClient.RestClient.cs b/src/Generated/LegacyCompletionClient.RestClient.cs new file mode 100644 index 000000000..2ef638da5 --- /dev/null +++ b/src/Generated/LegacyCompletionClient.RestClient.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.LegacyCompletions +{ + internal partial class LegacyCompletionClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateCompletionRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/completions", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/LegacyCompletionClient.cs b/src/Generated/LegacyCompletionClient.cs index 6ce310404..c2fe216ce 100644 --- a/src/Generated/LegacyCompletionClient.cs +++ b/src/Generated/LegacyCompletionClient.cs @@ -5,39 +5,31 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; +using System.Threading; using System.Threading.Tasks; +using OpenAI; namespace OpenAI.LegacyCompletions { - // Data plane generated sub-client. internal partial class LegacyCompletionClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected LegacyCompletionClient() { } - public virtual async Task> CreateCompletionAsync(InternalCreateCompletionRequest requestBody) - { - Argument.AssertNotNull(requestBody, nameof(requestBody)); + public ClientPipeline Pipeline { get; } - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = await CreateCompletionAsync(content, null).ConfigureAwait(false); - return ClientResult.FromValue(InternalCreateCompletionResponse.FromResponse(result.GetRawResponse()), result.GetRawResponse()); - } - - public virtual ClientResult CreateCompletion(InternalCreateCompletionRequest requestBody) + public virtual ClientResult CreateCompletion(BinaryContent content, RequestOptions options = null) { - Argument.AssertNotNull(requestBody, nameof(requestBody)); + Argument.AssertNotNull(content, nameof(content)); - using BinaryContent content = requestBody.ToBinaryContent(); - ClientResult result = CreateCompletion(content, null); - return ClientResult.FromValue(InternalCreateCompletionResponse.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + using PipelineMessage message = CreateCreateCompletionRequest(content, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } public virtual async Task CreateCompletionAsync(BinaryContent content, RequestOptions options = null) @@ -45,35 +37,23 @@ public virtual async Task CreateCompletionAsync(BinaryContent cont Argument.AssertNotNull(content, nameof(content)); using PipelineMessage message = CreateCreateCompletionRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - public virtual ClientResult CreateCompletion(BinaryContent content, RequestOptions options = null) + public virtual ClientResult CreateCompletion(InternalCreateCompletionRequest requestBody, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); - using PipelineMessage message = CreateCreateCompletionRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + ClientResult result = CreateCompletion(requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null); + return ClientResult.FromValue((InternalCreateCompletionResponse)result, result.GetRawResponse()); } - internal PipelineMessage CreateCreateCompletionRequest(BinaryContent content, RequestOptions options) + public virtual async Task> CreateCompletionAsync(InternalCreateCompletionRequest requestBody, CancellationToken cancellationToken = default) { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/completions", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } + Argument.AssertNotNull(requestBody, nameof(requestBody)); - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + ClientResult result = await CreateCompletionAsync(requestBody, cancellationToken.CanBeCanceled ? new RequestOptions { CancellationToken = cancellationToken } : null).ConfigureAwait(false); + return ClientResult.FromValue((InternalCreateCompletionResponse)result, result.GetRawResponse()); + } } } diff --git a/src/Generated/Models/Assistant.Serialization.cs b/src/Generated/Models/Assistant.Serialization.cs index 22f1b7a73..00bb5cd22 100644 --- a/src/Generated/Models/Assistant.Serialization.cs +++ b/src/Generated/Models/Assistant.Serialization.cs @@ -7,36 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class Assistant : IJsonModel { + internal Assistant() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(Assistant)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -45,10 +50,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("description") != true) + if (_additionalBinaryDataProperties?.ContainsKey("description") != true) { if (Description != null) { @@ -57,15 +62,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("description"); + writer.WriteNull("description"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("instructions") != true) { if (Instructions != null) { @@ -74,20 +79,20 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("instructions"); + writer.WriteNull("instructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ToolDefinition item in Tools) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) { if (ToolResources != null) { @@ -96,10 +101,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("tool_resources"); + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { @@ -108,16 +113,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -126,36 +136,41 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(NucleusSamplingFactor)) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - if (NucleusSamplingFactor != null) + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) + { + if (ResponseFormat != null) { - writer.WritePropertyName("top_p"u8); - writer.WriteNumberValue(NucleusSamplingFactor.Value); + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); } else { - writer.WriteNull("top_p"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { - if (ResponseFormat != null) + if (NucleusSamplingFactor != null) { - writer.WritePropertyName("response_format"u8); - writer.WriteObjectValue(ResponseFormat, options); + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); } else { - writer.WriteNull("response_format"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -163,7 +178,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -172,31 +187,28 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions #endif } } - writer.WriteEndObject(); } - Assistant IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + Assistant IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual Assistant JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(Assistant)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistant(document.RootElement, options); } - internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderWriterOptions options = null) + internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalAssistantObjectObject @object = default; DateTimeOffset createdAt = default; string name = default; string description = default; @@ -206,137 +218,141 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW ToolResources toolResources = default; IReadOnlyDictionary metadata = default; float? temperature = default; - float? topP = default; + InternalAssistantObjectObject @object = default; AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float? nucleusSamplingFactor = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalAssistantObjectObject(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("description"u8)) + if (prop.NameEquals("description"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { description = null; continue; } - description = property.Value.GetString(); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { instructions = null; continue; } - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); } tools = array; continue; } - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { toolResources = null; continue; } - toolResources = ToolResources.DeserializeToolResources(property.Value, options); + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { metadata = new ChangeTrackingDictionary(); continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { temperature = null; continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("object"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + @object = new InternalAssistantObjectObject(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("response_format"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; + responseFormat = null; continue; } - topP = property.Value.GetSingle(); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + nucleusSamplingFactor = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + nucleusSamplingFactor = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new Assistant( id, - @object, createdAt, name, description, @@ -346,15 +362,17 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW toolResources, metadata, temperature, - topP, + @object, responseFormat, - serializedAdditionalRawData); + nucleusSamplingFactor, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -364,15 +382,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - Assistant IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + Assistant IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual Assistant 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistant(document.RootElement, options); } default: @@ -382,15 +401,20 @@ Assistant IPersistableModel.Create(BinaryData data, ModelReaderWriter string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static Assistant FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(Assistant assistant) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistant(document.RootElement); + if (assistant == null) + { + return null; + } + return BinaryContent.Create(assistant, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator Assistant(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistant(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/Assistant.cs b/src/Generated/Models/Assistant.cs index db507e169..91f89ae97 100644 --- a/src/Generated/Models/Assistant.cs +++ b/src/Generated/Models/Assistant.cs @@ -4,33 +4,29 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { public partial class Assistant { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IEnumerable tools, IReadOnlyDictionary metadata) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(model, nameof(model)); - Argument.AssertNotNull(tools, nameof(tools)); + private protected IDictionary _additionalBinaryDataProperties; + internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions) + { Id = id; CreatedAt = createdAt; Name = name; Description = description; Model = model; Instructions = instructions; - Tools = tools.ToList(); - Metadata = metadata; + Tools = new ChangeTrackingList(); + Metadata = new ChangeTrackingDictionary(); } - internal Assistant(string id, InternalAssistantObjectObject @object, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, ToolResources toolResources, IReadOnlyDictionary metadata, float? temperature, float? nucleusSamplingFactor, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, ToolResources toolResources, IReadOnlyDictionary metadata, float? temperature, InternalAssistantObjectObject @object, AssistantResponseFormat responseFormat, float? nucleusSamplingFactor, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; CreatedAt = createdAt; Name = name; Description = description; @@ -40,25 +36,36 @@ internal Assistant(string id, InternalAssistantObjectObject @object, DateTimeOff ToolResources = toolResources; Metadata = metadata; Temperature = temperature; - NucleusSamplingFactor = nucleusSamplingFactor; + this.Object = @object; ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal Assistant() - { + NucleusSamplingFactor = nucleusSamplingFactor; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public string Name { get; } + public string Description { get; } + public string Model { get; } + public string Instructions { get; } + public IReadOnlyList Tools { get; } + public ToolResources ToolResources { get; } + public IReadOnlyDictionary Metadata { get; } + public float? Temperature { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AssistantChatMessage.Serialization.cs b/src/Generated/Models/AssistantChatMessage.Serialization.cs index 2f58514e9..dd6564373 100644 --- a/src/Generated/Models/AssistantChatMessage.Serialization.cs +++ b/src/Generated/Models/AssistantChatMessage.Serialization.cs @@ -7,112 +7,159 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class AssistantChatMessage : IJsonModel { - AssistantChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + 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."); + throw new FormatException($"The model {nameof(AssistantChatMessage)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Refusal) && _additionalBinaryDataProperties?.ContainsKey("refusal") != true) + { + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"u8); + } + } + if (Optional.IsDefined(ParticipantName) && _additionalBinaryDataProperties?.ContainsKey("name") != true) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(ParticipantName); + } + if (Optional.IsCollectionDefined(ToolCalls) && _additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (ChatToolCall item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall) && _additionalBinaryDataProperties?.ContainsKey("function_call") != true) + { + if (FunctionCall != null) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionCall, options); + } + else + { + writer.WriteNull("functionCall"u8); + } } + } + + AssistantChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (AssistantChatMessage)JsonModelCreateCore(ref reader, options); + 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, options); } - internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantChatMessage DeserializeAssistantChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + Chat.ChatMessageRole role = default; + ChatMessageContent content = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string refusal = default; - string name = default; + string participantName = default; IList toolCalls = default; ChatFunctionCall functionCall = default; - ChatMessageRole role = default; - ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("refusal"u8)) + 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 (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { refusal = null; continue; } - refusal = property.Value.GetString(); + refusal = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + participantName = prop.Value.GetString(); continue; } - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatToolCall.DeserializeChatToolCall(item, options)); } toolCalls = array; continue; } - if (property.NameEquals("function_call"u8)) + if (prop.NameEquals("function_call"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { functionCall = null; continue; } - functionCall = ChatFunctionCall.DeserializeChatFunctionCall(property.Value, options); - continue; - } - if (property.NameEquals("role"u8)) - { - role = property.Value.GetString().ToChatMessageRole(); - continue; - } - if (property.NameEquals("content"u8)) - { - DeserializeContentValue(property, ref content); + functionCall = ChatFunctionCall.DeserializeChatFunctionCall(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. return new AssistantChatMessage( role, content ?? new ChatMessageContent(), - serializedAdditionalRawData, + additionalBinaryDataProperties, refusal, - name, + participantName, toolCalls ?? new ChangeTrackingList(), functionCall); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -122,15 +169,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - AssistantChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (AssistantChatMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistantChatMessage(document.RootElement, options); } default: @@ -140,15 +188,20 @@ AssistantChatMessage IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new AssistantChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AssistantChatMessage assistantChatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantChatMessage(document.RootElement); + if (assistantChatMessage == null) + { + return null; + } + return BinaryContent.Create(assistantChatMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator AssistantChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistantChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AssistantChatMessage.cs b/src/Generated/Models/AssistantChatMessage.cs index b87f78891..e93ddae80 100644 --- a/src/Generated/Models/AssistantChatMessage.cs +++ b/src/Generated/Models/AssistantChatMessage.cs @@ -9,7 +9,7 @@ namespace OpenAI.Chat { public partial class AssistantChatMessage : ChatMessage { - internal AssistantChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData) + internal AssistantChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, additionalBinaryDataProperties) { Refusal = refusal; ParticipantName = participantName; diff --git a/src/Generated/Models/AssistantCollectionOrder.cs b/src/Generated/Models/AssistantCollectionOrder.cs index 2b25b8450..41d2f8d50 100644 --- a/src/Generated/Models/AssistantCollectionOrder.cs +++ b/src/Generated/Models/AssistantCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct AssistantCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public AssistantCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(AssistantCollectionOrder left, AssistantCollectionOrder right) => left.Equals(right); + public static bool operator !=(AssistantCollectionOrder left, AssistantCollectionOrder right) => !left.Equals(right); + public static implicit operator AssistantCollectionOrder(string value) => new AssistantCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is AssistantCollectionOrder other && Equals(other); + public bool Equals(AssistantCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/AssistantCreationOptions.Serialization.cs b/src/Generated/Models/AssistantCreationOptions.Serialization.cs index 31be626be..b74e1cf0e 100644 --- a/src/Generated/Models/AssistantCreationOptions.Serialization.cs +++ b/src/Generated/Models/AssistantCreationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,19 +15,19 @@ public partial class AssistantCreationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AssistantCreationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); - } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -35,10 +36,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(Description)) + if (Optional.IsDefined(Description) && _additionalBinaryDataProperties?.ContainsKey("description") != true) { if (Description != null) { @@ -47,10 +48,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("description"); + writer.WriteNull("description"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(Instructions)) + if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { if (Instructions != null) { @@ -59,32 +60,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("instructions"); + writer.WriteNull("instructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) - { - writer.WritePropertyName("tools"u8); - writer.WriteStartArray(); - foreach (var item in Tools) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) - { - if (ToolResources != null) - { - writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); - } - else - { - writer.WriteNull("tool_resources"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -93,16 +72,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -111,22 +95,37 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(NucleusSamplingFactor)) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { - if (NucleusSamplingFactor != null) + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (ToolDefinition item in Tools) { - writer.WritePropertyName("top_p"u8); - writer.WriteNumberValue(NucleusSamplingFactor.Value); + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); } else { - writer.WriteNull("top_p"); + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { if (ResponseFormat != null) { @@ -135,12 +134,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("response_format"); + writer.WriteNull("responseFormat"u8); + } + } + if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) + { + if (NucleusSamplingFactor != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + else + { + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -148,7 +159,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -157,171 +168,174 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead #endif } } - writer.WriteEndObject(); } - AssistantCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AssistantCreationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AssistantCreationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistantCreationOptions(document.RootElement, options); } - internal static AssistantCreationOptions DeserializeAssistantCreationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantCreationOptions DeserializeAssistantCreationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string model = default; string name = default; string description = default; string instructions = default; - IList tools = default; - ToolResources toolResources = default; IDictionary metadata = default; float? temperature = default; - float? topP = default; + string model = default; + IList tools = default; + ToolResources toolResources = default; AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float? nucleusSamplingFactor = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) - { - model = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("description"u8)) + if (prop.NameEquals("description"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { description = null; continue; } - description = property.Value.GetString(); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { instructions = null; continue; } - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) { - array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } - tools = array; + metadata = dictionary; continue; } - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolResources = null; + temperature = null; continue; } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + model = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("tools"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); } - metadata = dictionary; + tools = array; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - temperature = null; + toolResources = null; continue; } - temperature = property.Value.GetSingle(); + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; + responseFormat = null; continue; } - topP = property.Value.GetSingle(); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + nucleusSamplingFactor = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + nucleusSamplingFactor = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AssistantCreationOptions( - model, name, description, instructions, - tools ?? new ChangeTrackingList(), - toolResources, metadata ?? new ChangeTrackingDictionary(), temperature, - topP, + model, + tools ?? new ChangeTrackingList(), + toolResources, responseFormat, - serializedAdditionalRawData); + nucleusSamplingFactor, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -331,15 +345,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - AssistantCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AssistantCreationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistantCreationOptions(document.RootElement, options); } default: @@ -349,15 +364,20 @@ AssistantCreationOptions IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AssistantCreationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AssistantCreationOptions assistantCreationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantCreationOptions(document.RootElement); + if (assistantCreationOptions == null) + { + return null; + } + return BinaryContent.Create(assistantCreationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AssistantCreationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistantCreationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AssistantCreationOptions.cs b/src/Generated/Models/AssistantCreationOptions.cs index 9e0ed5afc..ebc4e3202 100644 --- a/src/Generated/Models/AssistantCreationOptions.cs +++ b/src/Generated/Models/AssistantCreationOptions.cs @@ -9,26 +9,37 @@ namespace OpenAI.Assistants { public partial class AssistantCreationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal AssistantCreationOptions(string model, string name, string description, string instructions, IList tools, ToolResources toolResources, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal AssistantCreationOptions(string name, string description, string instructions, IDictionary metadata, float? temperature, string model, IList tools, ToolResources toolResources, AssistantResponseFormat responseFormat, float? nucleusSamplingFactor, IDictionary additionalBinaryDataProperties) { - Model = model; Name = name; Description = description; Instructions = instructions; - Tools = tools; - ToolResources = toolResources; Metadata = metadata; Temperature = temperature; - NucleusSamplingFactor = nucleusSamplingFactor; + Model = model; + Tools = tools; + ToolResources = toolResources; ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; + NucleusSamplingFactor = nucleusSamplingFactor; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Name { get; set; } + public string Description { get; set; } + public string Instructions { get; set; } + public IDictionary Metadata { get; set; } + public float? Temperature { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AssistantDeletionResult.Serialization.cs b/src/Generated/Models/AssistantDeletionResult.Serialization.cs index 85b760cd0..d6203fb79 100644 --- a/src/Generated/Models/AssistantDeletionResult.Serialization.cs +++ b/src/Generated/Models/AssistantDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class AssistantDeletionResult : IJsonModel { + internal AssistantDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AssistantDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(AssistantId); - } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Deleted); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(AssistantId); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - AssistantDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AssistantDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AssistantDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistantDeletionResult(document.RootElement, options); } - internal static AssistantDeletionResult DeserializeAssistantDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantDeletionResult DeserializeAssistantDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; bool deleted = default; + string assistantId = default; InternalDeleteAssistantResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("id"u8)) { - deleted = property.Value.GetBoolean(); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteAssistantResponseObject(property.Value.GetString()); + @object = new InternalDeleteAssistantResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new AssistantDeletionResult(id, deleted, @object, serializedAdditionalRawData); + return new AssistantDeletionResult(deleted, assistantId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - AssistantDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AssistantDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistantDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ AssistantDeletionResult IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AssistantDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AssistantDeletionResult assistantDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantDeletionResult(document.RootElement); + if (assistantDeletionResult == null) + { + return null; + } + return BinaryContent.Create(assistantDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AssistantDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistantDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AssistantDeletionResult.cs b/src/Generated/Models/AssistantDeletionResult.cs index 7736dd664..fbd0d0574 100644 --- a/src/Generated/Models/AssistantDeletionResult.cs +++ b/src/Generated/Models/AssistantDeletionResult.cs @@ -9,26 +9,28 @@ namespace OpenAI.Assistants { public partial class AssistantDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal AssistantDeletionResult(string assistantId, bool deleted) - { - Argument.AssertNotNull(assistantId, nameof(assistantId)); + private protected IDictionary _additionalBinaryDataProperties; - AssistantId = assistantId; + internal AssistantDeletionResult(bool deleted, string assistantId) + { Deleted = deleted; + AssistantId = assistantId; } - internal AssistantDeletionResult(string assistantId, bool deleted, InternalDeleteAssistantResponseObject @object, IDictionary serializedAdditionalRawData) + internal AssistantDeletionResult(bool deleted, string assistantId, InternalDeleteAssistantResponseObject @object, IDictionary additionalBinaryDataProperties) { - AssistantId = assistantId; Deleted = deleted; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + AssistantId = assistantId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal AssistantDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public bool Deleted { get; } } } diff --git a/src/Generated/Models/AssistantModificationOptions.Serialization.cs b/src/Generated/Models/AssistantModificationOptions.Serialization.cs index 185f0d9bc..d60696f6a 100644 --- a/src/Generated/Models/AssistantModificationOptions.Serialization.cs +++ b/src/Generated/Models/AssistantModificationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,19 +15,19 @@ public partial class AssistantModificationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AssistantModificationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); - } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -35,10 +36,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(Description)) + if (Optional.IsDefined(Description) && _additionalBinaryDataProperties?.ContainsKey("description") != true) { if (Description != null) { @@ -47,10 +48,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("description"); + writer.WriteNull("description"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(Instructions)) + if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { if (Instructions != null) { @@ -59,32 +60,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("instructions"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(DefaultTools)) - { - writer.WritePropertyName("tools"u8); - writer.WriteStartArray(); - foreach (var item in DefaultTools) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) - { - if (ToolResources != null) - { - writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); - } - else - { - writer.WriteNull("tool_resources"); + writer.WriteNull("instructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -93,16 +72,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -111,22 +95,37 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(NucleusSamplingFactor)) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { - if (NucleusSamplingFactor != null) + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (Optional.IsCollectionDefined(DefaultTools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (ToolDefinition item in DefaultTools) { - writer.WritePropertyName("top_p"u8); - writer.WriteNumberValue(NucleusSamplingFactor.Value); + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); } else { - writer.WriteNull("top_p"); + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { if (ResponseFormat != null) { @@ -135,12 +134,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("response_format"); + writer.WriteNull("responseFormat"u8); + } + } + if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) + { + if (NucleusSamplingFactor != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + else + { + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -148,7 +159,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -157,171 +168,174 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - AssistantModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AssistantModificationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AssistantModificationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistantModificationOptions(document.RootElement, options); } - internal static AssistantModificationOptions DeserializeAssistantModificationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantModificationOptions DeserializeAssistantModificationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string model = default; string name = default; string description = default; string instructions = default; - IList tools = default; - ToolResources toolResources = default; IDictionary metadata = default; float? temperature = default; - float? topP = default; + string model = default; + IList defaultTools = default; + ToolResources toolResources = default; AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float? nucleusSamplingFactor = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) - { - model = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("description"u8)) + if (prop.NameEquals("description"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { description = null; continue; } - description = property.Value.GetString(); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { instructions = null; continue; } - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) { - array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } - tools = array; + metadata = dictionary; continue; } - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolResources = null; + temperature = null; continue; } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); + temperature = prop.Value.GetSingle(); + continue; + } + if (prop.NameEquals("model"u8)) + { + model = prop.Value.GetString(); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); } - metadata = dictionary; + defaultTools = array; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - temperature = null; + toolResources = null; continue; } - temperature = property.Value.GetSingle(); + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; + responseFormat = null; continue; } - topP = property.Value.GetSingle(); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + nucleusSamplingFactor = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + nucleusSamplingFactor = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AssistantModificationOptions( - model, name, description, instructions, - tools ?? new ChangeTrackingList(), - toolResources, metadata ?? new ChangeTrackingDictionary(), temperature, - topP, + model, + defaultTools ?? new ChangeTrackingList(), + toolResources, responseFormat, - serializedAdditionalRawData); + nucleusSamplingFactor, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -331,15 +345,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - AssistantModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AssistantModificationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistantModificationOptions(document.RootElement, options); } default: @@ -349,15 +364,20 @@ AssistantModificationOptions IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AssistantModificationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AssistantModificationOptions assistantModificationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantModificationOptions(document.RootElement); + if (assistantModificationOptions == null) + { + return null; + } + return BinaryContent.Create(assistantModificationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AssistantModificationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistantModificationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AssistantModificationOptions.cs b/src/Generated/Models/AssistantModificationOptions.cs index baa7fed1a..3019103f5 100644 --- a/src/Generated/Models/AssistantModificationOptions.cs +++ b/src/Generated/Models/AssistantModificationOptions.cs @@ -4,36 +4,49 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class AssistantModificationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public AssistantModificationOptions() { - DefaultTools = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); + DefaultTools = new ChangeTrackingList(); } - internal AssistantModificationOptions(string model, string name, string description, string instructions, IList defaultTools, ToolResources toolResources, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal AssistantModificationOptions(string name, string description, string instructions, IDictionary metadata, float? temperature, string model, IList defaultTools, ToolResources toolResources, AssistantResponseFormat responseFormat, float? nucleusSamplingFactor, IDictionary additionalBinaryDataProperties) { - Model = model; Name = name; Description = description; Instructions = instructions; - DefaultTools = defaultTools; - ToolResources = toolResources; Metadata = metadata; Temperature = temperature; - NucleusSamplingFactor = nucleusSamplingFactor; + Model = model; + DefaultTools = defaultTools; + ToolResources = toolResources; ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; + NucleusSamplingFactor = nucleusSamplingFactor; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Name { get; set; } + public string Description { get; set; } + public string Instructions { get; set; } + public IDictionary Metadata { get; set; } + public float? Temperature { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AssistantResponseFormat.Serialization.cs b/src/Generated/Models/AssistantResponseFormat.Serialization.cs index f2fa4d9f9..8b20f6949 100644 --- a/src/Generated/Models/AssistantResponseFormat.Serialization.cs +++ b/src/Generated/Models/AssistantResponseFormat.Serialization.cs @@ -6,11 +6,102 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(InternalUnknownAssistantResponseFormat))] - public partial class AssistantResponseFormat : IJsonModel + public abstract partial class AssistantResponseFormat : IJsonModel { + internal AssistantResponseFormat() + { + } + + 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(AssistantResponseFormat)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + protected virtual AssistantResponseFormat 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(AssistantResponseFormat)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return AssistantResponseFormat.DeserializeAssistantResponseFormat(document.RootElement, options); + } + + 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); + default: + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + protected virtual AssistantResponseFormat 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)) + { + return AssistantResponseFormat.DeserializeAssistantResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + public static implicit operator BinaryContent(AssistantResponseFormat assistantResponseFormat) + { + if (assistantResponseFormat == null) + { + return null; + } + return BinaryContent.Create(assistantResponseFormat, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator AssistantResponseFormat(ClientResult result) + { + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return AssistantResponseFormat.DeserializeAssistantResponseFormat(document.RootElement, ModelSerializationExtensions.WireOptions); + } } } diff --git a/src/Generated/Models/AssistantResponseFormat.cs b/src/Generated/Models/AssistantResponseFormat.cs index 3490f8a5a..d10278603 100644 --- a/src/Generated/Models/AssistantResponseFormat.cs +++ b/src/Generated/Models/AssistantResponseFormat.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { public abstract partial class AssistantResponseFormat { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected AssistantResponseFormat() + private protected IDictionary _additionalBinaryDataProperties; + + private protected AssistantResponseFormat(string @type) { + Type = @type; } - internal AssistantResponseFormat(string type, IDictionary serializedAdditionalRawData) + internal AssistantResponseFormat(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AssistantThread.Serialization.cs b/src/Generated/Models/AssistantThread.Serialization.cs index 45e72b9bf..d2c44e115 100644 --- a/src/Generated/Models/AssistantThread.Serialization.cs +++ b/src/Generated/Models/AssistantThread.Serialization.cs @@ -7,48 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class AssistantThread : IJsonModel { + internal AssistantThread() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AssistantThread)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true) - { - if (ToolResources != null) - { - writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); - } - else - { - writer.WriteNull("tool_resources"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { @@ -57,18 +50,40 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); + } + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -76,7 +91,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -85,98 +100,101 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO #endif } } - writer.WriteEndObject(); } - AssistantThread IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantThread IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AssistantThread JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AssistantThread)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAssistantThread(document.RootElement, options); } - internal static AssistantThread DeserializeAssistantThread(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantThread DeserializeAssistantThread(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalThreadObjectObject @object = default; DateTimeOffset createdAt = default; - ToolResources toolResources = default; IReadOnlyDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalThreadObjectObject @object = default; + ToolResources toolResources = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalThreadObjectObject(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolResources = null; + metadata = new ChangeTrackingDictionary(); continue; } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; + continue; + } + if (prop.NameEquals("object"u8)) + { + @object = new InternalThreadObjectObject(prop.Value.GetString()); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - metadata = new ChangeTrackingDictionary(); + toolResources = null; continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AssistantThread( id, - @object, createdAt, - toolResources, metadata, - serializedAdditionalRawData); + @object, + toolResources, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -186,15 +204,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - AssistantThread IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantThread IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AssistantThread 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAssistantThread(document.RootElement, options); } default: @@ -204,15 +223,20 @@ AssistantThread IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AssistantThread FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AssistantThread assistantThread) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantThread(document.RootElement); + if (assistantThread == null) + { + return null; + } + return BinaryContent.Create(assistantThread, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AssistantThread(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAssistantThread(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AssistantThread.cs b/src/Generated/Models/AssistantThread.cs index 6cec49e4b..ffdf0bed5 100644 --- a/src/Generated/Models/AssistantThread.cs +++ b/src/Generated/Models/AssistantThread.cs @@ -4,39 +4,42 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class AssistantThread { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal AssistantThread(string id, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata) - { - Argument.AssertNotNull(id, nameof(id)); + private protected IDictionary _additionalBinaryDataProperties; + internal AssistantThread(string id, DateTimeOffset createdAt, ToolResources toolResources) + { Id = id; CreatedAt = createdAt; + Metadata = new ChangeTrackingDictionary(); ToolResources = toolResources; - Metadata = metadata; } - internal AssistantThread(string id, InternalThreadObjectObject @object, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantThread(string id, DateTimeOffset createdAt, IReadOnlyDictionary metadata, InternalThreadObjectObject @object, ToolResources toolResources, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; CreatedAt = createdAt; - ToolResources = toolResources; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal AssistantThread() - { + this.Object = @object; + ToolResources = toolResources; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public IReadOnlyDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AudioTranscription.Serialization.cs b/src/Generated/Models/AudioTranscription.Serialization.cs index d08be5d13..8ed9f26bb 100644 --- a/src/Generated/Models/AudioTranscription.Serialization.cs +++ b/src/Generated/Models/AudioTranscription.Serialization.cs @@ -7,63 +7,73 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { public partial class AudioTranscription : IJsonModel { + internal AudioTranscription() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AudioTranscription)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("task") != true) - { - writer.WritePropertyName("task"u8); - writer.WriteStringValue(Task.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("language") != true) + if (_additionalBinaryDataProperties?.ContainsKey("language") != true) { writer.WritePropertyName("language"u8); writer.WriteStringValue(Language); } - if (SerializedAdditionalRawData?.ContainsKey("duration") != true) - { - writer.WritePropertyName("duration"u8); - writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); - } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("words") != true && Optional.IsCollectionDefined(Words)) + if (true && Optional.IsCollectionDefined(Words) && _additionalBinaryDataProperties?.ContainsKey("words") != true) { writer.WritePropertyName("words"u8); writer.WriteStartArray(); - foreach (var item in Words) + foreach (TranscribedWord item in Words) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("segments") != true && Optional.IsCollectionDefined(Segments)) + if (true && Optional.IsCollectionDefined(Segments) && _additionalBinaryDataProperties?.ContainsKey("segments") != true) { writer.WritePropertyName("segments"u8); writer.WriteStartArray(); - foreach (var item in Segments) + foreach (TranscribedSegment item in Segments) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("task") != true) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(Task.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("duration") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -71,7 +81,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -80,108 +90,104 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - AudioTranscription IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AudioTranscription IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AudioTranscription JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AudioTranscription)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAudioTranscription(document.RootElement, options); } - internal static AudioTranscription DeserializeAudioTranscription(JsonElement element, ModelReaderWriterOptions options = null) + internal static AudioTranscription DeserializeAudioTranscription(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalCreateTranscriptionResponseVerboseJsonTask task = default; string language = default; - TimeSpan? duration = default; string text = default; IReadOnlyList words = default; IReadOnlyList segments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalCreateTranscriptionResponseVerboseJsonTask task = default; + TimeSpan? duration = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("task"u8)) + if (prop.NameEquals("language"u8)) { - task = new InternalCreateTranscriptionResponseVerboseJsonTask(property.Value.GetString()); + language = prop.Value.GetString(); continue; } - if (property.NameEquals("language"u8)) + if (prop.NameEquals("text"u8)) { - language = property.Value.GetString(); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("duration"u8)) + if (prop.NameEquals("words"u8)) { - duration = TimeSpan.FromSeconds(property.Value.GetDouble()); - continue; - } - if (property.NameEquals("text"u8)) - { - text = property.Value.GetString(); - continue; - } - if (property.NameEquals("words"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(TranscribedWord.DeserializeTranscribedWord(item, options)); } words = array; continue; } - if (property.NameEquals("segments"u8)) + if (prop.NameEquals("segments"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(TranscribedSegment.DeserializeTranscribedSegment(item, options)); } segments = array; continue; } + if (prop.NameEquals("task"u8)) + { + task = new InternalCreateTranscriptionResponseVerboseJsonTask(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = TimeSpan.FromSeconds(prop.Value.GetDouble()); + continue; + } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AudioTranscription( - task, language, - duration, text, words ?? new ChangeTrackingList(), segments ?? new ChangeTrackingList(), - serializedAdditionalRawData); + task, + duration, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -191,15 +197,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - AudioTranscription IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AudioTranscription IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AudioTranscription 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAudioTranscription(document.RootElement, options); } default: @@ -209,9 +216,20 @@ AudioTranscription IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal virtual BinaryContent ToBinaryContent() + public static implicit operator BinaryContent(AudioTranscription audioTranscription) + { + if (audioTranscription == null) + { + return null; + } + return BinaryContent.Create(audioTranscription, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator AudioTranscription(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscription(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AudioTranscription.cs b/src/Generated/Models/AudioTranscription.cs index ce9824521..687b2f3cb 100644 --- a/src/Generated/Models/AudioTranscription.cs +++ b/src/Generated/Models/AudioTranscription.cs @@ -4,42 +4,46 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Audio { public partial class AudioTranscription { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal AudioTranscription(string language, TimeSpan? duration, string text) - { - Argument.AssertNotNull(language, nameof(language)); - Argument.AssertNotNull(text, nameof(text)); + private protected IDictionary _additionalBinaryDataProperties; + internal AudioTranscription(string language, string text, TimeSpan? duration) + { Language = language; - Duration = duration; Text = text; Words = new ChangeTrackingList(); Segments = new ChangeTrackingList(); + Duration = duration; } - internal AudioTranscription(InternalCreateTranscriptionResponseVerboseJsonTask task, string language, TimeSpan? duration, string text, IReadOnlyList words, IReadOnlyList segments, IDictionary serializedAdditionalRawData) + internal AudioTranscription(string language, string text, IReadOnlyList words, IReadOnlyList segments, InternalCreateTranscriptionResponseVerboseJsonTask task, TimeSpan? duration, IDictionary additionalBinaryDataProperties) { - Task = task; Language = language; - Duration = duration; Text = text; Words = words; Segments = segments; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal AudioTranscription() - { + Task = task; + Duration = duration; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Language { get; } + public string Text { get; } + public IReadOnlyList Words { get; } + public IReadOnlyList Segments { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AudioTranscriptionFormat.cs b/src/Generated/Models/AudioTranscriptionFormat.cs index 7903416bc..0c2834261 100644 --- a/src/Generated/Models/AudioTranscriptionFormat.cs +++ b/src/Generated/Models/AudioTranscriptionFormat.cs @@ -4,33 +4,40 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { public readonly partial struct AudioTranscriptionFormat : IEquatable { private readonly string _value; + private const string JsonValue = "json"; + private const string TextValue = "text"; + private const string SrtValue = "srt"; + private const string VerboseJsonValue = "verbose_json"; + private const string VttValue = "vtt"; public AudioTranscriptionFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string SimpleValue = "json"; - private const string TextValue = "text"; - private const string SrtValue = "srt"; - private const string VerboseValue = "verbose_json"; - private const string VttValue = "vtt"; public static bool operator ==(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => left.Equals(right); + public static bool operator !=(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => !left.Equals(right); + public static implicit operator AudioTranscriptionFormat(string value) => new AudioTranscriptionFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is AudioTranscriptionFormat other && Equals(other); + public bool Equals(AudioTranscriptionFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/AudioTranscriptionOptions.Serialization.cs b/src/Generated/Models/AudioTranscriptionOptions.Serialization.cs index 6ea4d80b9..6834f5fda 100644 --- a/src/Generated/Models/AudioTranscriptionOptions.Serialization.cs +++ b/src/Generated/Models/AudioTranscriptionOptions.Serialization.cs @@ -6,8 +6,8 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; -using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { @@ -15,55 +15,53 @@ public partial class AudioTranscriptionOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AudioTranscriptionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file") != true) - { - writer.WritePropertyName("file"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(File); -#else - using (JsonDocument document = JsonDocument.Parse(File)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("language") != true && Optional.IsDefined(Language)) + if (Optional.IsDefined(Language) && _additionalBinaryDataProperties?.ContainsKey("language") != true) { writer.WritePropertyName("language"u8); writer.WriteStringValue(Language); } - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true && Optional.IsDefined(Prompt)) + if (Optional.IsDefined(Prompt) && _additionalBinaryDataProperties?.ContainsKey("prompt") != true) { writer.WritePropertyName("prompt"u8); writer.WriteStringValue(Prompt); } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { writer.WritePropertyName("response_format"u8); writer.WriteStringValue(ResponseFormat.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { writer.WritePropertyName("temperature"u8); writer.WriteNumberValue(Temperature.Value); } - if (SerializedAdditionalRawData?.ContainsKey("timestamp_granularities[]") != true && Optional.IsCollectionDefined(InternalTimestampGranularities)) + if (_additionalBinaryDataProperties?.ContainsKey("file") != true) + { + writer.WritePropertyName("file"u8); + writer.WriteBase64StringValue(File.ToArray(), "D"); + } + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model.ToString()); + } + if (Optional.IsCollectionDefined(InternalTimestampGranularities) && _additionalBinaryDataProperties?.ContainsKey("timestamp_granularities[]") != true) { writer.WritePropertyName("timestamp_granularities[]"u8); writer.WriteStartArray(); - foreach (var item in InternalTimestampGranularities) + foreach (BinaryData item in InternalTimestampGranularities) { if (item == null) { @@ -71,7 +69,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea continue; } #if NET6_0_OR_GREATER - writer.WriteRawValue(item); + writer.WriteRawValue(item); #else using (JsonDocument document = JsonDocument.Parse(item)) { @@ -81,9 +79,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -91,7 +89,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -100,86 +98,83 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - AudioTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AudioTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AudioTranscriptionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAudioTranscriptionOptions(document.RootElement, options); } - internal static AudioTranscriptionOptions DeserializeAudioTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static AudioTranscriptionOptions DeserializeAudioTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - BinaryData file = default; - InternalCreateTranscriptionRequestModel model = default; string language = default; string prompt = default; AudioTranscriptionFormat? responseFormat = default; float? temperature = default; - IList timestampGranularities = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData @file = default; + InternalCreateTranscriptionRequestModel model = default; + IList internalTimestampGranularities = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file"u8)) + if (prop.NameEquals("language"u8)) { - file = BinaryData.FromString(property.Value.GetRawText()); + language = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("prompt"u8)) { - model = new InternalCreateTranscriptionRequestModel(property.Value.GetString()); + prompt = prop.Value.GetString(); continue; } - if (property.NameEquals("language"u8)) + if (prop.NameEquals("response_format"u8)) { - language = property.Value.GetString(); - continue; - } - if (property.NameEquals("prompt"u8)) - { - prompt = property.Value.GetString(); - continue; - } - if (property.NameEquals("response_format"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - responseFormat = new AudioTranscriptionFormat(property.Value.GetString()); + responseFormat = new AudioTranscriptionFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); + continue; + } + if (prop.NameEquals("file"u8)) + { + @file = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); + continue; + } + if (prop.NameEquals("model"u8)) + { + model = new InternalCreateTranscriptionRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("timestamp_granularities[]"u8)) + if (prop.NameEquals("timestamp_granularities[]"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { @@ -190,97 +185,49 @@ internal static AudioTranscriptionOptions DeserializeAudioTranscriptionOptions(J array.Add(BinaryData.FromString(item.GetRawText())); } } - timestampGranularities = array; + internalTimestampGranularities = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AudioTranscriptionOptions( - file, - model, language, prompt, responseFormat, temperature, - timestampGranularities ?? new ChangeTrackingList(), - serializedAdditionalRawData); + @file, + model, + internalTimestampGranularities ?? new ChangeTrackingList(), + additionalBinaryDataProperties); } - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(File, "file", "file"); - content.Add(Model.ToString(), "model"); - if (Optional.IsDefined(Language)) - { - content.Add(Language, "language"); - } - if (Optional.IsDefined(Prompt)) - { - content.Add(Prompt, "prompt"); - } - if (Optional.IsDefined(ResponseFormat)) - { - content.Add(ResponseFormat.Value.ToString(), "response_format"); - } - if (Optional.IsDefined(Temperature)) - { - content.Add(Temperature.Value, "temperature"); - } - if (Optional.IsCollectionDefined(InternalTimestampGranularities)) - { - foreach (BinaryData item in InternalTimestampGranularities) - { - content.Add(item, "timestamp_granularities[]", "timestamp_granularities[]"); - } - } - return content; - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support writing '{options.Format}' format."); } } - AudioTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AudioTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AudioTranscriptionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAudioTranscriptionOptions(document.RootElement, options); } default: @@ -288,17 +235,22 @@ AudioTranscriptionOptions IPersistableModel.Create(Bi } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AudioTranscriptionOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AudioTranscriptionOptions audioTranscriptionOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAudioTranscriptionOptions(document.RootElement); + if (audioTranscriptionOptions == null) + { + return null; + } + return BinaryContent.Create(audioTranscriptionOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AudioTranscriptionOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscriptionOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AudioTranscriptionOptions.cs b/src/Generated/Models/AudioTranscriptionOptions.cs index 041086b2f..bad6872f1 100644 --- a/src/Generated/Models/AudioTranscriptionOptions.cs +++ b/src/Generated/Models/AudioTranscriptionOptions.cs @@ -9,22 +9,32 @@ namespace OpenAI.Audio { public partial class AudioTranscriptionOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal AudioTranscriptionOptions(BinaryData file, InternalCreateTranscriptionRequestModel model, string language, string prompt, AudioTranscriptionFormat? responseFormat, float? temperature, IList internalTimestampGranularities, IDictionary serializedAdditionalRawData) + internal AudioTranscriptionOptions(string language, string prompt, AudioTranscriptionFormat? responseFormat, float? temperature, BinaryData @file, InternalCreateTranscriptionRequestModel model, IList internalTimestampGranularities, IDictionary additionalBinaryDataProperties) { - File = file; - Model = model; Language = language; Prompt = prompt; ResponseFormat = responseFormat; Temperature = temperature; + File = @file; + Model = model; InternalTimestampGranularities = internalTimestampGranularities; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Language { get; set; } + public string Prompt { get; set; } + public AudioTranscriptionFormat? ResponseFormat { get; set; } + public float? Temperature { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AudioTranslation.Serialization.cs b/src/Generated/Models/AudioTranslation.Serialization.cs index ff7da0c0b..425466132 100644 --- a/src/Generated/Models/AudioTranslation.Serialization.cs +++ b/src/Generated/Models/AudioTranslation.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { public partial class AudioTranslation : IJsonModel { + internal AudioTranslation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AudioTranslation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("task") != true) - { - writer.WritePropertyName("task"u8); - writer.WriteStringValue(Task.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("language") != true) + if (_additionalBinaryDataProperties?.ContainsKey("language") != true) { writer.WritePropertyName("language"u8); writer.WriteStringValue(Language); } - if (SerializedAdditionalRawData?.ContainsKey("duration") != true) - { - writer.WritePropertyName("duration"u8); - writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); - } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("segments") != true && Optional.IsCollectionDefined(Segments)) + if (true && Optional.IsCollectionDefined(Segments) && _additionalBinaryDataProperties?.ContainsKey("segments") != true) { writer.WritePropertyName("segments"u8); writer.WriteStartArray(); - foreach (var item in Segments) + foreach (TranscribedSegment item in Segments) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("task") != true) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(Task.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("duration") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,92 +80,88 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - AudioTranslation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AudioTranslation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AudioTranslation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AudioTranslation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAudioTranslation(document.RootElement, options); } - internal static AudioTranslation DeserializeAudioTranslation(JsonElement element, ModelReaderWriterOptions options = null) + internal static AudioTranslation DeserializeAudioTranslation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalCreateTranslationResponseVerboseJsonTask task = default; string language = default; - TimeSpan? duration = default; string text = default; IReadOnlyList segments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalCreateTranslationResponseVerboseJsonTask task = default; + TimeSpan? duration = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("task"u8)) + if (prop.NameEquals("language"u8)) { - task = new InternalCreateTranslationResponseVerboseJsonTask(property.Value.GetString()); + language = prop.Value.GetString(); continue; } - if (property.NameEquals("language"u8)) + if (prop.NameEquals("text"u8)) { - language = property.Value.GetString(); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("duration"u8)) + if (prop.NameEquals("segments"u8)) { - duration = TimeSpan.FromSeconds(property.Value.GetDouble()); - continue; - } - if (property.NameEquals("text"u8)) - { - text = property.Value.GetString(); - continue; - } - if (property.NameEquals("segments"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(TranscribedSegment.DeserializeTranscribedSegment(item, options)); } segments = array; continue; } + if (prop.NameEquals("task"u8)) + { + task = new InternalCreateTranslationResponseVerboseJsonTask(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("duration"u8)) + { + duration = TimeSpan.FromSeconds(prop.Value.GetDouble()); + continue; + } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AudioTranslation( - task, language, - duration, text, segments ?? new ChangeTrackingList(), - serializedAdditionalRawData); + task, + duration, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -165,15 +171,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - AudioTranslation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AudioTranslation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AudioTranslation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAudioTranslation(document.RootElement, options); } default: @@ -183,9 +190,20 @@ AudioTranslation IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal virtual BinaryContent ToBinaryContent() + public static implicit operator BinaryContent(AudioTranslation audioTranslation) + { + if (audioTranslation == null) + { + return null; + } + return BinaryContent.Create(audioTranslation, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator AudioTranslation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranslation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AudioTranslation.cs b/src/Generated/Models/AudioTranslation.cs index 6dfb907ca..77f6d43eb 100644 --- a/src/Generated/Models/AudioTranslation.cs +++ b/src/Generated/Models/AudioTranslation.cs @@ -4,39 +4,42 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Audio { public partial class AudioTranslation { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal AudioTranslation(string language, TimeSpan? duration, string text) - { - Argument.AssertNotNull(language, nameof(language)); - Argument.AssertNotNull(text, nameof(text)); + private protected IDictionary _additionalBinaryDataProperties; + internal AudioTranslation(string language, string text, TimeSpan? duration) + { Language = language; - Duration = duration; Text = text; Segments = new ChangeTrackingList(); + Duration = duration; } - internal AudioTranslation(InternalCreateTranslationResponseVerboseJsonTask task, string language, TimeSpan? duration, string text, IReadOnlyList segments, IDictionary serializedAdditionalRawData) + internal AudioTranslation(string language, string text, IReadOnlyList segments, InternalCreateTranslationResponseVerboseJsonTask task, TimeSpan? duration, IDictionary additionalBinaryDataProperties) { - Task = task; Language = language; - Duration = duration; Text = text; Segments = segments; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal AudioTranslation() - { + Task = task; + Duration = duration; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Language { get; } + public string Text { get; } + public IReadOnlyList Segments { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/AudioTranslationFormat.cs b/src/Generated/Models/AudioTranslationFormat.cs index bcd682ce2..8d0be5459 100644 --- a/src/Generated/Models/AudioTranslationFormat.cs +++ b/src/Generated/Models/AudioTranslationFormat.cs @@ -4,33 +4,40 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { public readonly partial struct AudioTranslationFormat : IEquatable { private readonly string _value; + private const string JsonValue = "json"; + private const string TextValue = "text"; + private const string SrtValue = "srt"; + private const string VerboseJsonValue = "verbose_json"; + private const string VttValue = "vtt"; public AudioTranslationFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string SimpleValue = "json"; - private const string TextValue = "text"; - private const string SrtValue = "srt"; - private const string VerboseValue = "verbose_json"; - private const string VttValue = "vtt"; public static bool operator ==(AudioTranslationFormat left, AudioTranslationFormat right) => left.Equals(right); + public static bool operator !=(AudioTranslationFormat left, AudioTranslationFormat right) => !left.Equals(right); + public static implicit operator AudioTranslationFormat(string value) => new AudioTranslationFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is AudioTranslationFormat other && Equals(other); + public bool Equals(AudioTranslationFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/AudioTranslationOptions.Serialization.cs b/src/Generated/Models/AudioTranslationOptions.Serialization.cs index e2dc13746..d127fe2aa 100644 --- a/src/Generated/Models/AudioTranslationOptions.Serialization.cs +++ b/src/Generated/Models/AudioTranslationOptions.Serialization.cs @@ -6,8 +6,8 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; -using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { @@ -15,48 +15,46 @@ public partial class AudioTranslationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AudioTranslationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file") != true) - { - writer.WritePropertyName("file"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(File); -#else - using (JsonDocument document = JsonDocument.Parse(File)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true && Optional.IsDefined(Prompt)) + if (Optional.IsDefined(Prompt) && _additionalBinaryDataProperties?.ContainsKey("prompt") != true) { writer.WritePropertyName("prompt"u8); writer.WriteStringValue(Prompt); } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { writer.WritePropertyName("response_format"u8); writer.WriteStringValue(ResponseFormat.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { writer.WritePropertyName("temperature"u8); writer.WriteNumberValue(Temperature.Value); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("file") != true) + { + writer.WritePropertyName("file"u8); + writer.WriteBase64StringValue(File.ToArray(), "D"); + } + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model.ToString()); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -64,7 +62,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -73,146 +71,106 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - AudioTranslationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AudioTranslationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual AudioTranslationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeAudioTranslationOptions(document.RootElement, options); } - internal static AudioTranslationOptions DeserializeAudioTranslationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static AudioTranslationOptions DeserializeAudioTranslationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - BinaryData file = default; - InternalCreateTranslationRequestModel model = default; string prompt = default; AudioTranslationFormat? responseFormat = default; float? temperature = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData @file = default; + InternalCreateTranslationRequestModel model = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file"u8)) + if (prop.NameEquals("prompt"u8)) { - file = BinaryData.FromString(property.Value.GetRawText()); + prompt = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("response_format"u8)) { - model = new InternalCreateTranslationRequestModel(property.Value.GetString()); - continue; - } - if (property.NameEquals("prompt"u8)) - { - prompt = property.Value.GetString(); - continue; - } - if (property.NameEquals("response_format"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - responseFormat = new AudioTranslationFormat(property.Value.GetString()); + responseFormat = new AudioTranslationFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); + continue; + } + if (prop.NameEquals("file"u8)) + { + @file = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); + continue; + } + if (prop.NameEquals("model"u8)) + { + model = new InternalCreateTranslationRequestModel(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new AudioTranslationOptions( - file, - model, prompt, responseFormat, temperature, - serializedAdditionalRawData); - } - - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } + @file, + model, + additionalBinaryDataProperties); } - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() - { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(File, "file", "file"); - content.Add(Model.ToString(), "model"); - if (Optional.IsDefined(Prompt)) - { - content.Add(Prompt, "prompt"); - } - if (Optional.IsDefined(ResponseFormat)) - { - content.Add(ResponseFormat.Value.ToString(), "response_format"); - } - if (Optional.IsDefined(Temperature)) - { - content.Add(Temperature.Value, "temperature"); - } - return content; - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support writing '{options.Format}' format."); } } - AudioTranslationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AudioTranslationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual AudioTranslationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeAudioTranslationOptions(document.RootElement, options); } default: @@ -220,17 +178,22 @@ AudioTranslationOptions IPersistableModel.Create(Binary } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static AudioTranslationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(AudioTranslationOptions audioTranslationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAudioTranslationOptions(document.RootElement); + if (audioTranslationOptions == null) + { + return null; + } + return BinaryContent.Create(audioTranslationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator AudioTranslationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranslationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/AudioTranslationOptions.cs b/src/Generated/Models/AudioTranslationOptions.cs index a19d2f1fa..1af4b47a0 100644 --- a/src/Generated/Models/AudioTranslationOptions.cs +++ b/src/Generated/Models/AudioTranslationOptions.cs @@ -9,19 +9,28 @@ namespace OpenAI.Audio { public partial class AudioTranslationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal AudioTranslationOptions(BinaryData file, InternalCreateTranslationRequestModel model, string prompt, AudioTranslationFormat? responseFormat, float? temperature, IDictionary serializedAdditionalRawData) + internal AudioTranslationOptions(string prompt, AudioTranslationFormat? responseFormat, float? temperature, BinaryData @file, InternalCreateTranslationRequestModel model, IDictionary additionalBinaryDataProperties) { - File = file; - Model = model; Prompt = prompt; ResponseFormat = responseFormat; Temperature = temperature; - SerializedAdditionalRawData = serializedAdditionalRawData; + File = @file; + Model = model; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Prompt { get; set; } + public AudioTranslationFormat? ResponseFormat { get; set; } + public float? Temperature { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatCompletion.Serialization.cs b/src/Generated/Models/ChatCompletion.Serialization.cs index 5b586ea35..4d1bde5ac 100644 --- a/src/Generated/Models/ChatCompletion.Serialization.cs +++ b/src/Generated/Models/ChatCompletion.Serialization.cs @@ -7,46 +7,56 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatCompletion : IJsonModel { + internal ChatCompletion() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("choices") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { - writer.WritePropertyName("choices"u8); - writer.WriteStartArray(); - foreach (var item in Choices) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("created") != true) + if (Optional.IsDefined(SystemFingerprint) && _additionalBinaryDataProperties?.ContainsKey("system_fingerprint") != true) { - writer.WritePropertyName("created"u8); - writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (Optional.IsDefined(Usage) && _additionalBinaryDataProperties?.ContainsKey("usage") != true) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(ServiceTier)) + if (Optional.IsDefined(ServiceTier) && _additionalBinaryDataProperties?.ContainsKey("service_tier") != true) { if (ServiceTier != null) { @@ -55,27 +65,27 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } else { - writer.WriteNull("service_tier"); + writer.WriteNull("serviceTier"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) + if (_additionalBinaryDataProperties?.ContainsKey("choices") != true) { - writer.WritePropertyName("system_fingerprint"u8); - writer.WriteStringValue(SystemFingerprint); - } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (InternalCreateChatCompletionResponseChoice item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true && Optional.IsDefined(Usage)) + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) { - writer.WritePropertyName("usage"u8); - writer.WriteObjectValue(Usage, options); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -83,7 +93,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -92,118 +102,114 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp #endif } } - writer.WriteEndObject(); } - ChatCompletion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatCompletion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatCompletion JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + 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, options); } - internal static ChatCompletion DeserializeChatCompletion(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatCompletion DeserializeChatCompletion(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - IReadOnlyList choices = default; - DateTimeOffset created = default; string model = default; - InternalCreateChatCompletionResponseServiceTier? serviceTier = default; string systemFingerprint = default; - InternalCreateChatCompletionResponseObject @object = default; ChatTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalCreateChatCompletionResponseObject @object = default; + InternalCreateChatCompletionResponseServiceTier? serviceTier = default; + IReadOnlyList choices = default; + DateTimeOffset createdAt = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("choices"u8)) + if (prop.NameEquals("model"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(InternalCreateChatCompletionResponseChoice.DeserializeInternalCreateChatCompletionResponseChoice(item, options)); - } - choices = array; - continue; - } - if (property.NameEquals("created"u8)) - { - created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("system_fingerprint"u8)) { - model = property.Value.GetString(); + systemFingerprint = prop.Value.GetString(); continue; } - if (property.NameEquals("service_tier"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - serviceTier = null; continue; } - serviceTier = new InternalCreateChatCompletionResponseServiceTier(property.Value.GetString()); + usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, options); continue; } - if (property.NameEquals("system_fingerprint"u8)) + if (prop.NameEquals("object"u8)) { - systemFingerprint = property.Value.GetString(); + @object = new InternalCreateChatCompletionResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("service_tier"u8)) { - @object = new InternalCreateChatCompletionResponseObject(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + serviceTier = null; + continue; + } + serviceTier = new InternalCreateChatCompletionResponseServiceTier(prop.Value.GetString()); continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("choices"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - continue; + array.Add(InternalCreateChatCompletionResponseChoice.DeserializeInternalCreateChatCompletionResponseChoice(item, options)); } - usage = ChatTokenUsage.DeserializeChatTokenUsage(property.Value, options); + choices = array; + continue; + } + if (prop.NameEquals("created"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ChatCompletion( id, - choices, - created, model, - serviceTier, systemFingerprint, - @object, usage, - serializedAdditionalRawData); + @object, + serviceTier, + choices, + createdAt, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -213,15 +219,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - ChatCompletion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatCompletion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatCompletion(document.RootElement, options); } default: @@ -231,15 +238,20 @@ ChatCompletion IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatCompletion FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatCompletion chatCompletion) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatCompletion(document.RootElement); + if (chatCompletion == null) + { + return null; + } + return BinaryContent.Create(chatCompletion, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatCompletion(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletion(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatCompletion.cs b/src/Generated/Models/ChatCompletion.cs index e4a852ec6..c81c17e4c 100644 --- a/src/Generated/Models/ChatCompletion.cs +++ b/src/Generated/Models/ChatCompletion.cs @@ -10,40 +10,41 @@ namespace OpenAI.Chat { public partial class ChatCompletion { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ChatCompletion(string id, IEnumerable choices, DateTimeOffset createdAt, string model) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(choices, nameof(choices)); - Argument.AssertNotNull(model, nameof(model)); + private protected IDictionary _additionalBinaryDataProperties; + internal ChatCompletion(string id, string model, IEnumerable choices, DateTimeOffset createdAt) + { Id = id; + Model = model; Choices = choices.ToList(); CreatedAt = createdAt; - Model = model; } - internal ChatCompletion(string id, IReadOnlyList choices, DateTimeOffset createdAt, string model, InternalCreateChatCompletionResponseServiceTier? serviceTier, string systemFingerprint, InternalCreateChatCompletionResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal ChatCompletion(string id, string model, string systemFingerprint, ChatTokenUsage usage, InternalCreateChatCompletionResponseObject @object, InternalCreateChatCompletionResponseServiceTier? serviceTier, IReadOnlyList choices, DateTimeOffset createdAt, IDictionary additionalBinaryDataProperties) { Id = id; - Choices = choices; - CreatedAt = createdAt; Model = model; - ServiceTier = serviceTier; SystemFingerprint = systemFingerprint; - Object = @object; Usage = usage; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ChatCompletion() - { + this.Object = @object; + ServiceTier = serviceTier; + Choices = choices; + CreatedAt = createdAt; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public string Model { get; } + public string SystemFingerprint { get; } public ChatTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatCompletionOptions.Serialization.cs b/src/Generated/Models/ChatCompletionOptions.Serialization.cs index f164d3573..8f1a29eca 100644 --- a/src/Generated/Models/ChatCompletionOptions.Serialization.cs +++ b/src/Generated/Models/ChatCompletionOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,126 +15,92 @@ public partial class ChatCompletionOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatCompletionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("messages") != true) - { - writer.WritePropertyName("messages"u8); - SerializeMessagesValue(writer, options); - } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (Optional.IsDefined(FrequencyPenalty) && _additionalBinaryDataProperties?.ContainsKey("frequency_penalty") != true) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("store") != true && Optional.IsDefined(StoredOutputEnabled)) - { - if (StoredOutputEnabled != null) + if (FrequencyPenalty != null) { - writer.WritePropertyName("store"u8); - writer.WriteBooleanValue(StoredOutputEnabled.Value); + writer.WritePropertyName("frequency_penalty"u8); + writer.WriteNumberValue(FrequencyPenalty.Value); } else { - writer.WriteNull("store"); + writer.WriteNull("frequencyPenalty"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsDefined(PresencePenalty) && _additionalBinaryDataProperties?.ContainsKey("presence_penalty") != true) { - if (Metadata != null) + if (PresencePenalty != null) { - writer.WritePropertyName("metadata"u8); - writer.WriteStartObject(); - foreach (var item in Metadata) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); + writer.WritePropertyName("presence_penalty"u8); + writer.WriteNumberValue(PresencePenalty.Value); } else { - writer.WriteNull("metadata"); + writer.WriteNull("presencePenalty"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("frequency_penalty") != true && Optional.IsDefined(FrequencyPenalty)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { - if (FrequencyPenalty != null) - { - writer.WritePropertyName("frequency_penalty"u8); - writer.WriteNumberValue(FrequencyPenalty.Value); - } - else - { - writer.WriteNull("frequency_penalty"); - } + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); } - if (SerializedAdditionalRawData?.ContainsKey("logit_bias") != true && Optional.IsCollectionDefined(LogitBiases)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { - if (LogitBiases != null) + if (Temperature != null) { - writer.WritePropertyName("logit_bias"u8); - SerializeLogitBiasesValue(writer, options); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); } else { - writer.WriteNull("logit_bias"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("logprobs") != true && Optional.IsDefined(IncludeLogProbabilities)) + if (Optional.IsDefined(TopP) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { - if (IncludeLogProbabilities != null) + if (TopP != null) { - writer.WritePropertyName("logprobs"u8); - writer.WriteBooleanValue(IncludeLogProbabilities.Value); + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); } else { - writer.WriteNull("logprobs"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_logprobs") != true && Optional.IsDefined(TopLogProbabilityCount)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { - if (TopLogProbabilityCount != null) - { - writer.WritePropertyName("top_logprobs"u8); - writer.WriteNumberValue(TopLogProbabilityCount.Value); - } - else + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (ChatTool item in Tools) { - writer.WriteNull("top_logprobs"); + writer.WriteObjectValue(item, options); } + writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("max_tokens") != true && Optional.IsDefined(_deprecatedMaxTokens)) + if (_additionalBinaryDataProperties?.ContainsKey("messages") != true) { - if (_deprecatedMaxTokens != null) - { - writer.WritePropertyName("max_tokens"u8); - writer.WriteNumberValue(_deprecatedMaxTokens.Value); - } - else - { - writer.WriteNull("max_tokens"); - } + writer.WritePropertyName("messages"u8); + this.SerializeMessagesValue(writer, options); } - if (SerializedAdditionalRawData?.ContainsKey("max_completion_tokens") != true && Optional.IsDefined(MaxOutputTokenCount)) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { - if (MaxOutputTokenCount != null) - { - writer.WritePropertyName("max_completion_tokens"u8); - writer.WriteNumberValue(MaxOutputTokenCount.Value); - } - else - { - writer.WriteNull("max_completion_tokens"); - } + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("n") != true && Optional.IsDefined(N)) + if (Optional.IsDefined(N) && _additionalBinaryDataProperties?.ContainsKey("n") != true) { if (N != null) { @@ -142,153 +109,197 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } else { - writer.WriteNull("n"); + writer.WriteNull("n"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("presence_penalty") != true && Optional.IsDefined(PresencePenalty)) + if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true) { - if (PresencePenalty != null) + if (Stream != null) { - writer.WritePropertyName("presence_penalty"u8); - writer.WriteNumberValue(PresencePenalty.Value); + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); } else { - writer.WriteNull("presence_penalty"); + writer.WriteNull("stream"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(StreamOptions) && _additionalBinaryDataProperties?.ContainsKey("stream_options") != true) { - writer.WritePropertyName("response_format"u8); - writer.WriteObjectValue(ResponseFormat, options); + if (StreamOptions != null) + { + writer.WritePropertyName("stream_options"u8); + writer.WriteObjectValue(StreamOptions, options); + } + else + { + writer.WriteNull("streamOptions"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("seed") != true && Optional.IsDefined(Seed)) + if (Optional.IsDefined(IncludeLogProbabilities) && _additionalBinaryDataProperties?.ContainsKey("logprobs") != true) { - if (Seed != null) + if (IncludeLogProbabilities != null) { - writer.WritePropertyName("seed"u8); - writer.WriteNumberValue(Seed.Value); + writer.WritePropertyName("logprobs"u8); + writer.WriteBooleanValue(IncludeLogProbabilities.Value); } else { - writer.WriteNull("seed"); + writer.WriteNull("logprobs"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(_serviceTier)) + if (Optional.IsDefined(TopLogProbabilityCount) && _additionalBinaryDataProperties?.ContainsKey("top_logprobs") != true) { - if (_serviceTier != null) + if (TopLogProbabilityCount != null) { - writer.WritePropertyName("service_tier"u8); - writer.WriteStringValue(_serviceTier.Value.ToString()); + writer.WritePropertyName("top_logprobs"u8); + writer.WriteNumberValue(TopLogProbabilityCount.Value); } else { - writer.WriteNull("service_tier"); + writer.WriteNull("topLogprobs"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stop") != true && Optional.IsCollectionDefined(StopSequences)) + if (Optional.IsCollectionDefined(StopSequences) && _additionalBinaryDataProperties?.ContainsKey("stop") != true) { if (StopSequences != null) { writer.WritePropertyName("stop"u8); - SerializeStopSequencesValue(writer, options); + this.SerializeStopSequencesValue(writer, options); } else { - writer.WriteNull("stop"); + writer.WriteNull("stop"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stream") != true && Optional.IsDefined(Stream)) + if (Optional.IsCollectionDefined(LogitBiases) && _additionalBinaryDataProperties?.ContainsKey("logit_bias") != true) { - if (Stream != null) + if (LogitBiases != null) { - writer.WritePropertyName("stream"u8); - writer.WriteBooleanValue(Stream.Value); + writer.WritePropertyName("logit_bias"u8); + this.SerializeLogitBiasesValue(writer, options); } else { - writer.WriteNull("stream"); + writer.WriteNull("logitBias"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stream_options") != true && Optional.IsDefined(StreamOptions)) + if (Optional.IsDefined(ToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { - if (StreamOptions != null) + writer.WritePropertyName("tool_choice"u8); + writer.WriteObjectValue(ToolChoice, options); + } + if (Optional.IsDefined(FunctionChoice) && _additionalBinaryDataProperties?.ContainsKey("function_call") != true) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionChoice, options); + } + if (Optional.IsDefined(AllowParallelToolCalls) && _additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); + } + if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(EndUserId); + } + if (Optional.IsDefined(Seed) && _additionalBinaryDataProperties?.ContainsKey("seed") != true) + { + if (Seed != null) { - writer.WritePropertyName("stream_options"u8); - writer.WriteObjectValue(StreamOptions, options); + writer.WritePropertyName("seed"u8); + writer.WriteNumberValue(Seed.Value); } else { - writer.WriteNull("stream_options"); + writer.WriteNull("seed"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(_deprecatedMaxTokens) && _additionalBinaryDataProperties?.ContainsKey("max_tokens") != true) { - if (Temperature != null) + if (_deprecatedMaxTokens != null) { - writer.WritePropertyName("temperature"u8); - writer.WriteNumberValue(Temperature.Value); + writer.WritePropertyName("max_tokens"u8); + writer.WriteNumberValue(_deprecatedMaxTokens.Value); } else { - writer.WriteNull("temperature"); + writer.WriteNull("maxTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(TopP)) + if (Optional.IsDefined(MaxOutputTokenCount) && _additionalBinaryDataProperties?.ContainsKey("max_completion_tokens") != true) { - if (TopP != null) + if (MaxOutputTokenCount != null) { - writer.WritePropertyName("top_p"u8); - writer.WriteNumberValue(TopP.Value); + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxOutputTokenCount.Value); } else { - writer.WriteNull("top_p"); + writer.WriteNull("maxCompletionTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsCollectionDefined(Functions) && _additionalBinaryDataProperties?.ContainsKey("functions") != true) { - writer.WritePropertyName("tools"u8); + writer.WritePropertyName("functions"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ChatFunction item in Functions) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true && Optional.IsDefined(ToolChoice)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { - writer.WritePropertyName("tool_choice"u8); - writer.WriteObjectValue(ToolChoice, options); - } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(AllowParallelToolCalls)) - { - writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(AllowParallelToolCalls.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) - { - writer.WritePropertyName("user"u8); - writer.WriteStringValue(EndUserId); + if (Metadata != null) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("function_call") != true && Optional.IsDefined(FunctionChoice)) + if (Optional.IsDefined(StoredOutputEnabled) && _additionalBinaryDataProperties?.ContainsKey("store") != true) { - writer.WritePropertyName("function_call"u8); - writer.WriteObjectValue(FunctionChoice, options); + if (StoredOutputEnabled != null) + { + writer.WritePropertyName("store"u8); + writer.WriteBooleanValue(StoredOutputEnabled.Value); + } + else + { + writer.WriteNull("store"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("functions") != true && Optional.IsCollectionDefined(Functions)) + if (Optional.IsDefined(_serviceTier) && _additionalBinaryDataProperties?.ContainsKey("service_tier") != true) { - writer.WritePropertyName("functions"u8); - writer.WriteStartArray(); - foreach (var item in Functions) + if (_serviceTier != null) { - writer.WriteObjectValue(item, options); + writer.WritePropertyName("service_tier"u8); + writer.WriteStringValue(_serviceTier.Value.ToString()); + } + else + { + writer.WriteNull("serviceTier"u8); } - writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -296,7 +307,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -305,348 +316,351 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - ChatCompletionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatCompletionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatCompletionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatCompletionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatCompletionOptions(document.RootElement, options); } - internal static ChatCompletionOptions DeserializeChatCompletionOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatCompletionOptions DeserializeChatCompletionOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList messages = default; - InternalCreateChatCompletionRequestModel model = default; - bool? store = default; - IDictionary metadata = default; float? frequencyPenalty = default; - IDictionary logitBias = default; - bool? logprobs = default; - int? topLogprobs = default; - int? maxTokens = default; - int? maxCompletionTokens = default; - int? n = default; float? presencePenalty = default; ChatResponseFormat responseFormat = default; - long? seed = default; - InternalCreateChatCompletionRequestServiceTier? serviceTier = default; - IList stop = default; - bool? stream = default; - InternalChatCompletionStreamOptions streamOptions = default; float? temperature = default; float? topP = default; IList tools = default; + IList messages = default; + InternalCreateChatCompletionRequestModel model = default; + int? n = default; + bool? stream = default; + InternalChatCompletionStreamOptions streamOptions = default; + bool? includeLogProbabilities = default; + int? topLogProbabilityCount = default; + IList stopSequences = default; + IDictionary logitBiases = default; ChatToolChoice toolChoice = default; - bool? parallelToolCalls = default; - string user = default; - ChatFunctionChoice functionCall = default; + ChatFunctionChoice functionChoice = default; + bool? allowParallelToolCalls = default; + string endUserId = default; + long? seed = default; + int? deprecatedMaxTokens = default; + int? maxOutputTokenCount = default; IList functions = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary metadata = default; + bool? storedOutputEnabled = default; + InternalCreateChatCompletionRequestServiceTier? serviceTier = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("messages"u8)) + if (prop.NameEquals("frequency_penalty"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + if (prop.Value.ValueKind == JsonValueKind.Null) { - array.Add(ChatMessage.DeserializeChatMessage(item, options)); + frequencyPenalty = null; + continue; } - messages = array; - continue; - } - if (property.NameEquals("model"u8)) - { - model = new InternalCreateChatCompletionRequestModel(property.Value.GetString()); + frequencyPenalty = prop.Value.GetSingle(); continue; } - if (property.NameEquals("store"u8)) + if (prop.NameEquals("presence_penalty"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - store = null; + presencePenalty = null; continue; } - store = property.Value.GetBoolean(); + presencePenalty = prop.Value.GetSingle(); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + responseFormat = ChatResponseFormat.DeserializeChatResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("frequency_penalty"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - frequencyPenalty = null; + temperature = null; continue; } - frequencyPenalty = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("logit_bias"u8)) + if (prop.NameEquals("top_p"u8)) { - DeserializeLogitBiasesValue(property, ref logitBias); - continue; - } - if (property.NameEquals("logprobs"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - logprobs = null; + topP = null; continue; } - logprobs = property.Value.GetBoolean(); + topP = prop.Value.GetSingle(); continue; } - if (property.NameEquals("top_logprobs"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - topLogprobs = null; continue; } - topLogprobs = property.Value.GetInt32(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ChatTool.DeserializeChatTool(item, options)); + } + tools = array; continue; } - if (property.NameEquals("max_tokens"u8)) + if (prop.NameEquals("messages"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - maxTokens = null; - continue; + array.Add(ChatMessage.DeserializeChatMessage(item, options)); } - maxTokens = property.Value.GetInt32(); + messages = array; continue; } - if (property.NameEquals("max_completion_tokens"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - maxCompletionTokens = null; - continue; - } - maxCompletionTokens = property.Value.GetInt32(); + model = new InternalCreateChatCompletionRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("n"u8)) + if (prop.NameEquals("n"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { n = null; continue; } - n = property.Value.GetInt32(); + n = prop.Value.GetInt32(); continue; } - if (property.NameEquals("presence_penalty"u8)) + if (prop.NameEquals("stream"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - presencePenalty = null; + stream = null; continue; } - presencePenalty = property.Value.GetSingle(); + stream = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("stream_options"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + streamOptions = null; continue; } - responseFormat = ChatResponseFormat.DeserializeChatResponseFormat(property.Value, options); + streamOptions = InternalChatCompletionStreamOptions.DeserializeInternalChatCompletionStreamOptions(prop.Value, options); continue; } - if (property.NameEquals("seed"u8)) + if (prop.NameEquals("logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - seed = null; + includeLogProbabilities = null; continue; } - seed = property.Value.GetInt64(); + includeLogProbabilities = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("service_tier"u8)) + if (prop.NameEquals("top_logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - serviceTier = null; + topLogProbabilityCount = null; continue; } - serviceTier = new InternalCreateChatCompletionRequestServiceTier(property.Value.GetString()); + topLogProbabilityCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("stop"u8)) + if (prop.NameEquals("stop"u8)) { - DeserializeStopSequencesValue(property, ref stop); + DeserializeStopSequencesValue(prop, ref stopSequences); continue; } - if (property.NameEquals("stream"u8)) + if (prop.NameEquals("logit_bias"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + DeserializeLogitBiasesValue(prop, ref logitBiases); + continue; + } + if (prop.NameEquals("tool_choice"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - stream = null; continue; } - stream = property.Value.GetBoolean(); + toolChoice = ChatToolChoice.DeserializeChatToolChoice(prop.Value, options); continue; } - if (property.NameEquals("stream_options"u8)) + if (prop.NameEquals("function_call"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - streamOptions = null; continue; } - streamOptions = InternalChatCompletionStreamOptions.DeserializeInternalChatCompletionStreamOptions(property.Value, options); + functionChoice = ChatFunctionChoice.DeserializeChatFunctionChoice(prop.Value, options); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("parallel_tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - temperature = null; continue; } - temperature = property.Value.GetSingle(); + allowParallelToolCalls = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("user"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + endUserId = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("seed"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; + seed = null; continue; } - topP = property.Value.GetSingle(); + seed = prop.Value.GetInt64(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("max_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + deprecatedMaxTokens = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ChatTool.DeserializeChatTool(item, options)); - } - tools = array; + deprecatedMaxTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("max_completion_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + maxOutputTokenCount = null; continue; } - toolChoice = ChatToolChoice.DeserializeChatToolChoice(property.Value, options); + maxOutputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("parallel_tool_calls"u8)) + if (prop.NameEquals("functions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - parallelToolCalls = property.Value.GetBoolean(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ChatFunction.DeserializeChatFunction(item, options)); + } + functions = array; continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("metadata"u8)) { - user = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("function_call"u8)) + if (prop.NameEquals("store"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + storedOutputEnabled = null; continue; } - functionCall = ChatFunctionChoice.DeserializeChatFunctionChoice(property.Value, options); + storedOutputEnabled = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("functions"u8)) + if (prop.NameEquals("service_tier"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + serviceTier = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ChatFunction.DeserializeChatFunction(item, options)); - } - functions = array; + serviceTier = new InternalCreateChatCompletionRequestServiceTier(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ChatCompletionOptions( - messages, - model, - store, - metadata ?? new ChangeTrackingDictionary(), frequencyPenalty, - logitBias ?? new ChangeTrackingDictionary(), - logprobs, - topLogprobs, - maxTokens, - maxCompletionTokens, - n, presencePenalty, responseFormat, - seed, - serviceTier, - stop ?? new ChangeTrackingList(), - stream, - streamOptions, temperature, topP, tools ?? new ChangeTrackingList(), + messages, + model, + n, + stream, + streamOptions, + includeLogProbabilities, + topLogProbabilityCount, + stopSequences ?? new ChangeTrackingList(), + logitBiases ?? new ChangeTrackingDictionary(), toolChoice, - parallelToolCalls, - user, - functionCall, + functionChoice, + allowParallelToolCalls, + endUserId, + seed, + deprecatedMaxTokens, + maxOutputTokenCount, functions ?? new ChangeTrackingList(), - serializedAdditionalRawData); + metadata ?? new ChangeTrackingDictionary(), + storedOutputEnabled, + serviceTier, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -656,15 +670,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - ChatCompletionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatCompletionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatCompletionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatCompletionOptions(document.RootElement, options); } default: @@ -674,15 +689,20 @@ ChatCompletionOptions IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatCompletionOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatCompletionOptions chatCompletionOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatCompletionOptions(document.RootElement); + if (chatCompletionOptions == null) + { + return null; + } + return BinaryContent.Create(chatCompletionOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatCompletionOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatCompletionOptions.cs b/src/Generated/Models/ChatCompletionOptions.cs index 68127ece8..431b4bed0 100644 --- a/src/Generated/Models/ChatCompletionOptions.cs +++ b/src/Generated/Models/ChatCompletionOptions.cs @@ -4,49 +4,60 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.Chat { public partial class ChatCompletionOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatCompletionOptions(IList messages, InternalCreateChatCompletionRequestModel model, bool? storedOutputEnabled, IDictionary metadata, float? frequencyPenalty, IDictionary logitBiases, bool? includeLogProbabilities, int? topLogProbabilityCount, int? deprecatedMaxTokens, int? maxOutputTokenCount, int? n, float? presencePenalty, ChatResponseFormat responseFormat, long? seed, InternalCreateChatCompletionRequestServiceTier? serviceTier, IList stopSequences, bool? stream, InternalChatCompletionStreamOptions streamOptions, float? temperature, float? topP, IList tools, ChatToolChoice toolChoice, bool? allowParallelToolCalls, string endUserId, ChatFunctionChoice functionChoice, IList functions, IDictionary serializedAdditionalRawData) + internal ChatCompletionOptions(float? frequencyPenalty, float? presencePenalty, ChatResponseFormat responseFormat, float? temperature, float? topP, IList tools, IList messages, InternalCreateChatCompletionRequestModel model, int? n, bool? stream, InternalChatCompletionStreamOptions streamOptions, bool? includeLogProbabilities, int? topLogProbabilityCount, IList stopSequences, IDictionary logitBiases, ChatToolChoice toolChoice, ChatFunctionChoice functionChoice, bool? allowParallelToolCalls, string endUserId, long? seed, int? deprecatedMaxTokens, int? maxOutputTokenCount, IList functions, IDictionary metadata, bool? storedOutputEnabled, InternalCreateChatCompletionRequestServiceTier? serviceTier, IDictionary additionalBinaryDataProperties) { - Messages = messages; - Model = model; - StoredOutputEnabled = storedOutputEnabled; - Metadata = metadata; FrequencyPenalty = frequencyPenalty; - LogitBiases = logitBiases; - IncludeLogProbabilities = includeLogProbabilities; - TopLogProbabilityCount = topLogProbabilityCount; - _deprecatedMaxTokens = deprecatedMaxTokens; - MaxOutputTokenCount = maxOutputTokenCount; - N = n; PresencePenalty = presencePenalty; ResponseFormat = responseFormat; - Seed = seed; - _serviceTier = serviceTier; - StopSequences = stopSequences; - Stream = stream; - StreamOptions = streamOptions; Temperature = temperature; TopP = topP; Tools = tools; + Messages = messages; + Model = model; + N = n; + Stream = stream; + StreamOptions = streamOptions; + IncludeLogProbabilities = includeLogProbabilities; + TopLogProbabilityCount = topLogProbabilityCount; + StopSequences = stopSequences; + LogitBiases = logitBiases; ToolChoice = toolChoice; + FunctionChoice = functionChoice; AllowParallelToolCalls = allowParallelToolCalls; EndUserId = endUserId; - FunctionChoice = functionChoice; + Seed = seed; + _deprecatedMaxTokens = deprecatedMaxTokens; + MaxOutputTokenCount = maxOutputTokenCount; Functions = functions; - SerializedAdditionalRawData = serializedAdditionalRawData; + Metadata = metadata; + StoredOutputEnabled = storedOutputEnabled; + _serviceTier = serviceTier; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public float? FrequencyPenalty { get; set; } + public float? PresencePenalty { get; set; } + public ChatResponseFormat ResponseFormat { get; set; } + public float? Temperature { get; set; } + public float? TopP { get; set; } + public IList Tools { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatFinishReason.Serialization.cs b/src/Generated/Models/ChatFinishReason.Serialization.cs index 3bfd77465..63be95cef 100644 --- a/src/Generated/Models/ChatFinishReason.Serialization.cs +++ b/src/Generated/Models/ChatFinishReason.Serialization.cs @@ -8,23 +8,38 @@ namespace OpenAI.Chat { internal static partial class ChatFinishReasonExtensions { - public static string ToSerialString(this ChatFinishReason value) => value switch + public static string ToSerialString(this Chat.ChatFinishReason value) => value switch { - ChatFinishReason.Stop => "stop", - ChatFinishReason.Length => "length", - ChatFinishReason.ToolCalls => "tool_calls", - ChatFinishReason.ContentFilter => "content_filter", - ChatFinishReason.FunctionCall => "function_call", + Chat.ChatFinishReason.Stop => "stop", + Chat.ChatFinishReason.Length => "length", + Chat.ChatFinishReason.ToolCalls => "tool_calls", + Chat.ChatFinishReason.ContentFilter => "content_filter", + Chat.ChatFinishReason.FunctionCall => "function_call", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatFinishReason value.") }; - public static ChatFinishReason ToChatFinishReason(this string value) + public static Chat.ChatFinishReason ToChatFinishReason(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "stop")) return ChatFinishReason.Stop; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "length")) return ChatFinishReason.Length; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool_calls")) return ChatFinishReason.ToolCalls; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "content_filter")) return ChatFinishReason.ContentFilter; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "function_call")) return ChatFinishReason.FunctionCall; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "stop")) + { + return Chat.ChatFinishReason.Stop; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "length")) + { + return Chat.ChatFinishReason.Length; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool_calls")) + { + return Chat.ChatFinishReason.ToolCalls; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "content_filter")) + { + return Chat.ChatFinishReason.ContentFilter; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "function_call")) + { + return Chat.ChatFinishReason.FunctionCall; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatFinishReason value."); } } diff --git a/src/Generated/Models/ChatFunction.Serialization.cs b/src/Generated/Models/ChatFunction.Serialization.cs index 8974ea692..e3b1e78f5 100644 --- a/src/Generated/Models/ChatFunction.Serialization.cs +++ b/src/Generated/Models/ChatFunction.Serialization.cs @@ -7,35 +7,45 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatFunction : IJsonModel { + internal ChatFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(FunctionDescription)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(FunctionDescription); - } - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(FunctionName); } - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true && Optional.IsDefined(FunctionParameters)) + if (Optional.IsDefined(FunctionDescription) && _additionalBinaryDataProperties?.ContainsKey("description") != true) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(FunctionDescription); + } + if (Optional.IsDefined(FunctionParameters) && _additionalBinaryDataProperties?.ContainsKey("parameters") != true) { writer.WritePropertyName("parameters"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(FunctionParameters); + writer.WriteRawValue(FunctionParameters); #else using (JsonDocument document = JsonDocument.Parse(FunctionParameters)) { @@ -43,9 +53,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,69 +72,65 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti #endif } } - writer.WriteEndObject(); } - ChatFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatFunction(document.RootElement, options); } - internal static ChatFunction DeserializeChatFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatFunction DeserializeChatFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string description = default; - string name = default; - BinaryData parameters = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string functionName = default; + string functionDescription = default; + BinaryData functionParameters = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("description"u8)) + if (prop.NameEquals("name"u8)) { - description = property.Value.GetString(); + functionName = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("description"u8)) { - name = property.Value.GetString(); + functionDescription = prop.Value.GetString(); continue; } - if (property.NameEquals("parameters"u8)) + if (prop.NameEquals("parameters"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - parameters = BinaryData.FromString(property.Value.GetRawText()); + functionParameters = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatFunction(description, name, parameters, serializedAdditionalRawData); + return new ChatFunction(functionName, functionDescription, functionParameters, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions option } } - ChatFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatFunction(document.RootElement, options); } default: @@ -152,15 +159,20 @@ ChatFunction IPersistableModel.Create(BinaryData data, ModelReader string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatFunction chatFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatFunction(document.RootElement); + if (chatFunction == null) + { + return null; + } + return BinaryContent.Create(chatFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatFunction.cs b/src/Generated/Models/ChatFunction.cs index e3abf7d89..be1731278 100644 --- a/src/Generated/Models/ChatFunction.cs +++ b/src/Generated/Models/ChatFunction.cs @@ -9,18 +9,20 @@ namespace OpenAI.Chat { public partial class ChatFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatFunction(string functionDescription, string functionName, BinaryData functionParameters, IDictionary serializedAdditionalRawData) + internal ChatFunction(string functionName, string functionDescription, BinaryData functionParameters, IDictionary additionalBinaryDataProperties) { - FunctionDescription = functionDescription; FunctionName = functionName; + FunctionDescription = functionDescription; FunctionParameters = functionParameters; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatFunction() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatFunctionCall.Serialization.cs b/src/Generated/Models/ChatFunctionCall.Serialization.cs index a10c604ab..e5f6142b7 100644 --- a/src/Generated/Models/ChatFunctionCall.Serialization.cs +++ b/src/Generated/Models/ChatFunctionCall.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatFunctionCall : IJsonModel { + internal ChatFunctionCall() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatFunctionCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(FunctionName); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); - SerializeFunctionArgumentsValue(writer, options); + this.SerializeFunctionArgumentsValue(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - ChatFunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatFunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatFunctionCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatFunctionCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatFunctionCall(document.RootElement, options); } - internal static ChatFunctionCall DeserializeChatFunctionCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatFunctionCall DeserializeChatFunctionCall(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string name = default; - BinaryData arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string functionName = default; + BinaryData functionArguments = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + functionName = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - DeserializeFunctionArgumentsValue(property, ref arguments); + DeserializeFunctionArgumentsValue(prop, ref functionArguments); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatFunctionCall(name, arguments, serializedAdditionalRawData); + return new ChatFunctionCall(functionName, functionArguments, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ChatFunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatFunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatFunctionCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatFunctionCall(document.RootElement, options); } default: @@ -130,15 +137,20 @@ ChatFunctionCall IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatFunctionCall FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatFunctionCall chatFunctionCall) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatFunctionCall(document.RootElement); + if (chatFunctionCall == null) + { + return null; + } + return BinaryContent.Create(chatFunctionCall, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatFunctionCall(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatFunctionCall(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatFunctionCall.cs b/src/Generated/Models/ChatFunctionCall.cs index 23568c824..caa0f7c04 100644 --- a/src/Generated/Models/ChatFunctionCall.cs +++ b/src/Generated/Models/ChatFunctionCall.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { public partial class ChatFunctionCall { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ChatFunctionCall(string functionName, BinaryData functionArguments) { Argument.AssertNotNull(functionName, nameof(functionName)); @@ -19,15 +21,17 @@ public ChatFunctionCall(string functionName, BinaryData functionArguments) FunctionArguments = functionArguments; } - internal ChatFunctionCall(string functionName, BinaryData functionArguments, IDictionary serializedAdditionalRawData) + internal ChatFunctionCall(string functionName, BinaryData functionArguments, IDictionary additionalBinaryDataProperties) { FunctionName = functionName; FunctionArguments = functionArguments; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatFunctionCall() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatFunctionChoice.Serialization.cs b/src/Generated/Models/ChatFunctionChoice.Serialization.cs index eb482e954..4ec64d73c 100644 --- a/src/Generated/Models/ChatFunctionChoice.Serialization.cs +++ b/src/Generated/Models/ChatFunctionChoice.Serialization.cs @@ -6,27 +6,58 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatFunctionChoice : IJsonModel { - ChatFunctionChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ChatFunctionChoice)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatFunctionChoice)} does not support writing '{format}' format."); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + ChatFunctionChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatFunctionChoice 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(ChatFunctionChoice)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatFunctionChoice(document.RootElement, options); + return ChatFunctionChoice.DeserializeChatFunctionChoice(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +67,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ChatFunctionChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatFunctionChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatFunctionChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeChatFunctionChoice(document.RootElement, options); + return ChatFunctionChoice.DeserializeChatFunctionChoice(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ChatFunctionChoice)} does not support reading '{options.Format}' format."); @@ -54,15 +86,20 @@ ChatFunctionChoice IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatFunctionChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatFunctionChoice chatFunctionChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatFunctionChoice(document.RootElement); + if (chatFunctionChoice == null) + { + return null; + } + return BinaryContent.Create(chatFunctionChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatFunctionChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ChatFunctionChoice.DeserializeChatFunctionChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatFunctionChoice.cs b/src/Generated/Models/ChatFunctionChoice.cs index a103d4f41..1eda67818 100644 --- a/src/Generated/Models/ChatFunctionChoice.cs +++ b/src/Generated/Models/ChatFunctionChoice.cs @@ -9,6 +9,12 @@ namespace OpenAI.Chat { public partial class ChatFunctionChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatImageDetailLevel.cs b/src/Generated/Models/ChatImageDetailLevel.cs index 28d44ae56..485f3a13d 100644 --- a/src/Generated/Models/ChatImageDetailLevel.cs +++ b/src/Generated/Models/ChatImageDetailLevel.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { public readonly partial struct ChatImageDetailLevel : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; public ChatImageDetailLevel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LowValue = "low"; - private const string HighValue = "high"; + _value = value; + } public static ChatImageDetailLevel Auto { get; } = new ChatImageDetailLevel(AutoValue); + public static ChatImageDetailLevel Low { get; } = new ChatImageDetailLevel(LowValue); + public static ChatImageDetailLevel High { get; } = new ChatImageDetailLevel(HighValue); + public static bool operator ==(ChatImageDetailLevel left, ChatImageDetailLevel right) => left.Equals(right); + public static bool operator !=(ChatImageDetailLevel left, ChatImageDetailLevel right) => !left.Equals(right); + public static implicit operator ChatImageDetailLevel(string value) => new ChatImageDetailLevel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ChatImageDetailLevel other && Equals(other); + public bool Equals(ChatImageDetailLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ChatInputTokenUsageDetails.Serialization.cs b/src/Generated/Models/ChatInputTokenUsageDetails.Serialization.cs index 4b979bd87..0fac3b930 100644 --- a/src/Generated/Models/ChatInputTokenUsageDetails.Serialization.cs +++ b/src/Generated/Models/ChatInputTokenUsageDetails.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatInputTokenUsageDetails : IJsonModel { + internal ChatInputTokenUsageDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatInputTokenUsageDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("audio_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_tokens") != true) { writer.WritePropertyName("audio_tokens"u8); writer.WriteNumberValue(AudioTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("cached_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cached_tokens") != true) { writer.WritePropertyName("cached_tokens"u8); writer.WriteNumberValue(CachedTokenCount); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - ChatInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatInputTokenUsageDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatInputTokenUsageDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatInputTokenUsageDetails(document.RootElement, options); } - internal static ChatInputTokenUsageDetails DeserializeChatInputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatInputTokenUsageDetails DeserializeChatInputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int audioTokens = default; - int cachedTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int audioTokenCount = default; + int cachedTokenCount = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("audio_tokens"u8)) + if (prop.NameEquals("audio_tokens"u8)) { - audioTokens = property.Value.GetInt32(); + audioTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("cached_tokens"u8)) + if (prop.NameEquals("cached_tokens"u8)) { - cachedTokens = property.Value.GetInt32(); + cachedTokenCount = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatInputTokenUsageDetails(audioTokens, cachedTokens, serializedAdditionalRawData); + return new ChatInputTokenUsageDetails(audioTokenCount, cachedTokenCount, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - ChatInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatInputTokenUsageDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatInputTokenUsageDetails(document.RootElement, options); } default: @@ -130,15 +137,20 @@ ChatInputTokenUsageDetails IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatInputTokenUsageDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatInputTokenUsageDetails chatInputTokenUsageDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatInputTokenUsageDetails(document.RootElement); + if (chatInputTokenUsageDetails == null) + { + return null; + } + return BinaryContent.Create(chatInputTokenUsageDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatInputTokenUsageDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatInputTokenUsageDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatInputTokenUsageDetails.cs b/src/Generated/Models/ChatInputTokenUsageDetails.cs index bc46eb6a1..3fc955b5f 100644 --- a/src/Generated/Models/ChatInputTokenUsageDetails.cs +++ b/src/Generated/Models/ChatInputTokenUsageDetails.cs @@ -9,22 +9,25 @@ namespace OpenAI.Chat { public partial class ChatInputTokenUsageDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ChatInputTokenUsageDetails(int audioTokenCount, int cachedTokenCount) { AudioTokenCount = audioTokenCount; CachedTokenCount = cachedTokenCount; } - internal ChatInputTokenUsageDetails(int audioTokenCount, int cachedTokenCount, IDictionary serializedAdditionalRawData) + internal ChatInputTokenUsageDetails(int audioTokenCount, int cachedTokenCount, IDictionary additionalBinaryDataProperties) { AudioTokenCount = audioTokenCount; CachedTokenCount = cachedTokenCount; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatInputTokenUsageDetails() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatMessage.Serialization.cs b/src/Generated/Models/ChatMessage.Serialization.cs index 971105a95..b39d4ef3b 100644 --- a/src/Generated/Models/ChatMessage.Serialization.cs +++ b/src/Generated/Models/ChatMessage.Serialization.cs @@ -6,52 +6,95 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; -using OpenAI.FineTuning; +using OpenAI; namespace OpenAI.Chat { [PersistableModelProxy(typeof(InternalUnknownChatMessage))] public partial class ChatMessage : IJsonModel { - ChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessage)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) + { + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToSerialString()); + } + // CUSTOM: Check inner collection is defined. + if (true && Optional.IsDefined(Content) && Content.IsInnerCollectionDefined() && _additionalBinaryDataProperties?.ContainsKey("content") != true) + { + writer.WritePropertyName("content"u8); + this.SerializeContentValue(writer, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + ChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual 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(ChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatMessage(document.RootElement, options); } - internal static ChatMessage DeserializeChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatMessage DeserializeChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("role", out JsonElement discriminator)) + if (element.TryGetProperty("role"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case null: return InternalFineTuneChatCompletionRequestAssistantMessage.DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(element, options); - case "assistant": return AssistantChatMessage.DeserializeAssistantChatMessage(element, options); - case "function": return FunctionChatMessage.DeserializeFunctionChatMessage(element, options); - case "system": return SystemChatMessage.DeserializeSystemChatMessage(element, options); - case "tool": return ToolChatMessage.DeserializeToolChatMessage(element, options); - case "user": return UserChatMessage.DeserializeUserChatMessage(element, options); + case "system": + return SystemChatMessage.DeserializeSystemChatMessage(element, options); + case "user": + return UserChatMessage.DeserializeUserChatMessage(element, options); + case "assistant": + return AssistantChatMessage.DeserializeAssistantChatMessage(element, options); + case "tool": + return ToolChatMessage.DeserializeToolChatMessage(element, options); + case "function": + return FunctionChatMessage.DeserializeFunctionChatMessage(element, options); } } return InternalUnknownChatMessage.DeserializeInternalUnknownChatMessage(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -61,15 +104,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options } } - ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatMessage(document.RootElement, options); } default: @@ -79,15 +123,20 @@ ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWr string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatMessage chatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatMessage(document.RootElement); + if (chatMessage == null) + { + return null; + } + return BinaryContent.Create(chatMessage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatMessage.cs b/src/Generated/Models/ChatMessage.cs index 402d46474..368ee1c8d 100644 --- a/src/Generated/Models/ChatMessage.cs +++ b/src/Generated/Models/ChatMessage.cs @@ -9,13 +9,19 @@ namespace OpenAI.Chat { public partial class ChatMessage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData) + internal ChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties) { Role = role; Content = content; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatMessageContent.cs b/src/Generated/Models/ChatMessageContent.cs index 2ec5ca98d..c3e8dec13 100644 --- a/src/Generated/Models/ChatMessageContent.cs +++ b/src/Generated/Models/ChatMessageContent.cs @@ -2,11 +2,24 @@ #nullable disable -using System.Collections.ObjectModel; +using System; +using System.Collections.Generic; namespace OpenAI.Chat { - public partial class ChatMessageContent : Collection + public partial class ChatMessageContent { + private protected IDictionary _additionalBinaryDataProperties; + + internal ChatMessageContent(IDictionary additionalBinaryDataProperties) + { + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatMessageContentPart.Serialization.cs b/src/Generated/Models/ChatMessageContentPart.Serialization.cs index aa068ae4d..2cfaddfd1 100644 --- a/src/Generated/Models/ChatMessageContentPart.Serialization.cs +++ b/src/Generated/Models/ChatMessageContentPart.Serialization.cs @@ -6,27 +6,58 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatMessageContentPart : IJsonModel { - ChatMessageContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ChatMessageContentPart)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessageContentPart)} does not support writing '{format}' format."); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + ChatMessageContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatMessageContentPart 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(ChatMessageContentPart)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatMessageContentPart(document.RootElement, options); + return ChatMessageContentPart.DeserializeChatMessageContentPart(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +67,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - ChatMessageContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatMessageContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatMessageContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeChatMessageContentPart(document.RootElement, options); + return ChatMessageContentPart.DeserializeChatMessageContentPart(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ChatMessageContentPart)} does not support reading '{options.Format}' format."); @@ -54,15 +86,20 @@ ChatMessageContentPart IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatMessageContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatMessageContentPart chatMessageContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatMessageContentPart(document.RootElement); + if (chatMessageContentPart == null) + { + return null; + } + return BinaryContent.Create(chatMessageContentPart, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatMessageContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ChatMessageContentPart.DeserializeChatMessageContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatMessageContentPart.cs b/src/Generated/Models/ChatMessageContentPart.cs index ac4ef86e6..d6450c68e 100644 --- a/src/Generated/Models/ChatMessageContentPart.cs +++ b/src/Generated/Models/ChatMessageContentPart.cs @@ -9,6 +9,12 @@ namespace OpenAI.Chat { public partial class ChatMessageContentPart { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatMessageRole.Serialization.cs b/src/Generated/Models/ChatMessageRole.Serialization.cs index 4380b11e4..55d2b2eaf 100644 --- a/src/Generated/Models/ChatMessageRole.Serialization.cs +++ b/src/Generated/Models/ChatMessageRole.Serialization.cs @@ -8,23 +8,38 @@ namespace OpenAI.Chat { internal static partial class ChatMessageRoleExtensions { - public static string ToSerialString(this ChatMessageRole value) => value switch + public static string ToSerialString(this Chat.ChatMessageRole value) => value switch { - ChatMessageRole.System => "system", - ChatMessageRole.User => "user", - ChatMessageRole.Assistant => "assistant", - ChatMessageRole.Tool => "tool", - ChatMessageRole.Function => "function", + Chat.ChatMessageRole.System => "system", + Chat.ChatMessageRole.User => "user", + Chat.ChatMessageRole.Assistant => "assistant", + Chat.ChatMessageRole.Tool => "tool", + Chat.ChatMessageRole.Function => "function", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatMessageRole value.") }; - public static ChatMessageRole ToChatMessageRole(this string value) + public static Chat.ChatMessageRole ToChatMessageRole(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "system")) return ChatMessageRole.System; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "user")) return ChatMessageRole.User; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistant")) return ChatMessageRole.Assistant; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool")) return ChatMessageRole.Tool; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) return ChatMessageRole.Function; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "system")) + { + return Chat.ChatMessageRole.System; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "user")) + { + return Chat.ChatMessageRole.User; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistant")) + { + return Chat.ChatMessageRole.Assistant; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool")) + { + return Chat.ChatMessageRole.Tool; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) + { + return Chat.ChatMessageRole.Function; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatMessageRole value."); } } diff --git a/src/Generated/Models/ChatOutputTokenUsageDetails.Serialization.cs b/src/Generated/Models/ChatOutputTokenUsageDetails.Serialization.cs index 6e7808a0a..f6c672ead 100644 --- a/src/Generated/Models/ChatOutputTokenUsageDetails.Serialization.cs +++ b/src/Generated/Models/ChatOutputTokenUsageDetails.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatOutputTokenUsageDetails : IJsonModel { + internal ChatOutputTokenUsageDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatOutputTokenUsageDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("audio_tokens") != true) - { - writer.WritePropertyName("audio_tokens"u8); - writer.WriteNumberValue(AudioTokenCount); - } - if (SerializedAdditionalRawData?.ContainsKey("reasoning_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("reasoning_tokens") != true) { writer.WritePropertyName("reasoning_tokens"u8); writer.WriteNumberValue(ReasoningTokenCount); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("audio_tokens") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("audio_tokens"u8); + writer.WriteNumberValue(AudioTokenCount); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - ChatOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatOutputTokenUsageDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatOutputTokenUsageDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatOutputTokenUsageDetails(document.RootElement, options); } - internal static ChatOutputTokenUsageDetails DeserializeChatOutputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatOutputTokenUsageDetails DeserializeChatOutputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int audioTokens = default; - int reasoningTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int reasoningTokenCount = default; + int audioTokenCount = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("audio_tokens"u8)) + if (prop.NameEquals("reasoning_tokens"u8)) { - audioTokens = property.Value.GetInt32(); + reasoningTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("reasoning_tokens"u8)) + if (prop.NameEquals("audio_tokens"u8)) { - reasoningTokens = property.Value.GetInt32(); + audioTokenCount = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatOutputTokenUsageDetails(audioTokens, reasoningTokens, serializedAdditionalRawData); + return new ChatOutputTokenUsageDetails(reasoningTokenCount, audioTokenCount, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - ChatOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatOutputTokenUsageDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatOutputTokenUsageDetails(document.RootElement, options); } default: @@ -130,15 +137,20 @@ ChatOutputTokenUsageDetails IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatOutputTokenUsageDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatOutputTokenUsageDetails chatOutputTokenUsageDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatOutputTokenUsageDetails(document.RootElement); + if (chatOutputTokenUsageDetails == null) + { + return null; + } + return BinaryContent.Create(chatOutputTokenUsageDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatOutputTokenUsageDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatOutputTokenUsageDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatOutputTokenUsageDetails.cs b/src/Generated/Models/ChatOutputTokenUsageDetails.cs index 9225e4b7e..d6a3d4687 100644 --- a/src/Generated/Models/ChatOutputTokenUsageDetails.cs +++ b/src/Generated/Models/ChatOutputTokenUsageDetails.cs @@ -9,22 +9,25 @@ namespace OpenAI.Chat { public partial class ChatOutputTokenUsageDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ChatOutputTokenUsageDetails(int audioTokenCount, int reasoningTokenCount) + private protected IDictionary _additionalBinaryDataProperties; + + internal ChatOutputTokenUsageDetails(int reasoningTokenCount, int audioTokenCount) { - AudioTokenCount = audioTokenCount; ReasoningTokenCount = reasoningTokenCount; + AudioTokenCount = audioTokenCount; } - internal ChatOutputTokenUsageDetails(int audioTokenCount, int reasoningTokenCount, IDictionary serializedAdditionalRawData) + internal ChatOutputTokenUsageDetails(int reasoningTokenCount, int audioTokenCount, IDictionary additionalBinaryDataProperties) { - AudioTokenCount = audioTokenCount; ReasoningTokenCount = reasoningTokenCount; - SerializedAdditionalRawData = serializedAdditionalRawData; + AudioTokenCount = audioTokenCount; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatOutputTokenUsageDetails() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatResponseFormat.Serialization.cs b/src/Generated/Models/ChatResponseFormat.Serialization.cs index 26c297851..2cc1ea4bd 100644 --- a/src/Generated/Models/ChatResponseFormat.Serialization.cs +++ b/src/Generated/Models/ChatResponseFormat.Serialization.cs @@ -6,48 +6,85 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { [PersistableModelProxy(typeof(InternalUnknownChatResponseFormat))] public partial class ChatResponseFormat : IJsonModel { - ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual ChatResponseFormat 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(ChatResponseFormat)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatResponseFormat(document.RootElement, options); } - internal static ChatResponseFormat DeserializeChatResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatResponseFormat DeserializeChatResponseFormat(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "json_object": return InternalChatResponseFormatJsonObject.DeserializeInternalChatResponseFormatJsonObject(element, options); - case "json_schema": return InternalChatResponseFormatJsonSchema.DeserializeInternalChatResponseFormatJsonSchema(element, options); - case "text": return InternalChatResponseFormatText.DeserializeInternalChatResponseFormatText(element, options); + case "text": + return InternalChatResponseFormatText.DeserializeInternalChatResponseFormatText(element, options); + case "json_object": + return InternalChatResponseFormatJsonObject.DeserializeInternalChatResponseFormatJsonObject(element, options); + case "json_schema": + return InternalChatResponseFormatJsonSchema.DeserializeInternalChatResponseFormatJsonSchema(element, options); } } return InternalUnknownChatResponseFormat.DeserializeInternalUnknownChatResponseFormat(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -57,15 +94,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatResponseFormat(document.RootElement, options); } default: @@ -75,15 +113,20 @@ ChatResponseFormat IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatResponseFormat FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatResponseFormat chatResponseFormat) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatResponseFormat(document.RootElement); + if (chatResponseFormat == null) + { + return null; + } + return BinaryContent.Create(chatResponseFormat, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatResponseFormat(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatResponseFormat(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatResponseFormat.cs b/src/Generated/Models/ChatResponseFormat.cs index 45de78574..a904c8862 100644 --- a/src/Generated/Models/ChatResponseFormat.cs +++ b/src/Generated/Models/ChatResponseFormat.cs @@ -9,14 +9,25 @@ namespace OpenAI.Chat { public partial class ChatResponseFormat { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatResponseFormat(string type, IDictionary serializedAdditionalRawData) + private protected ChatResponseFormat(string @type) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + } + + internal ChatResponseFormat(string @type, IDictionary additionalBinaryDataProperties) + { + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatTokenLogProbabilityDetails.Serialization.cs b/src/Generated/Models/ChatTokenLogProbabilityDetails.Serialization.cs index eea644f3a..be762ab42 100644 --- a/src/Generated/Models/ChatTokenLogProbabilityDetails.Serialization.cs +++ b/src/Generated/Models/ChatTokenLogProbabilityDetails.Serialization.cs @@ -7,37 +7,47 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatTokenLogProbabilityDetails : IJsonModel { + internal ChatTokenLogProbabilityDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatTokenLogProbabilityDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("token") != true) + if (_additionalBinaryDataProperties?.ContainsKey("token") != true) { writer.WritePropertyName("token"u8); writer.WriteStringValue(Token); } - if (SerializedAdditionalRawData?.ContainsKey("logprob") != true) + if (_additionalBinaryDataProperties?.ContainsKey("logprob") != true) { writer.WritePropertyName("logprob"u8); writer.WriteNumberValue(LogProbability); } - if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + if (_additionalBinaryDataProperties?.ContainsKey("bytes") != true) { if (Utf8Bytes != null) { writer.WritePropertyName("bytes"u8); writer.WriteStartArray(); - foreach (var item in Utf8Bytes.Value.Span) + foreach (byte item in Utf8Bytes.Value.Span) { writer.WriteNumberValue(item); } @@ -45,22 +55,22 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } else { - writer.WriteNull("bytes"); + writer.WriteNull("bytes"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_logprobs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("top_logprobs") != true) { writer.WritePropertyName("top_logprobs"u8); writer.WriteStartArray(); - foreach (var item in TopLogProbabilities) + foreach (ChatTokenTopLogProbabilityDetails item in TopLogProbabilities) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -68,7 +78,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -77,87 +87,83 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod #endif } } - writer.WriteEndObject(); } - ChatTokenLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatTokenLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatTokenLogProbabilityDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatTokenLogProbabilityDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatTokenLogProbabilityDetails(document.RootElement, options); } - internal static ChatTokenLogProbabilityDetails DeserializeChatTokenLogProbabilityDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatTokenLogProbabilityDetails DeserializeChatTokenLogProbabilityDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string token = default; - float logprob = default; - ReadOnlyMemory? bytes = default; - IReadOnlyList topLogprobs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float logProbability = default; + ReadOnlyMemory? utf8Bytes = default; + IReadOnlyList topLogProbabilities = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("token"u8)) + if (prop.NameEquals("token"u8)) { - token = property.Value.GetString(); + token = prop.Value.GetString(); continue; } - if (property.NameEquals("logprob"u8)) + if (prop.NameEquals("logprob"u8)) { - logprob = property.Value.GetSingle(); + logProbability = prop.Value.GetSingle(); continue; } - if (property.NameEquals("bytes"u8)) + if (prop.NameEquals("bytes"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } int index = 0; - byte[] array = new byte[property.Value.GetArrayLength()]; - foreach (var item in property.Value.EnumerateArray()) + byte[] array = new byte[prop.Value.GetArrayLength()]; + foreach (var item in prop.Value.EnumerateArray()) { array[index] = item.GetByte(); index++; } - bytes = new ReadOnlyMemory?(array); + utf8Bytes = new ReadOnlyMemory(array); continue; } - if (property.NameEquals("top_logprobs"u8)) + if (prop.NameEquals("top_logprobs"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTokenTopLogProbabilityDetails.DeserializeChatTokenTopLogProbabilityDetails(item, options)); } - topLogprobs = array; + topLogProbabilities = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatTokenLogProbabilityDetails(token, logprob, bytes, topLogprobs, serializedAdditionalRawData); + return new ChatTokenLogProbabilityDetails(token, logProbability, utf8Bytes, topLogProbabilities, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -167,15 +173,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - ChatTokenLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatTokenLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatTokenLogProbabilityDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatTokenLogProbabilityDetails(document.RootElement, options); } default: @@ -185,15 +192,20 @@ ChatTokenLogProbabilityDetails IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatTokenLogProbabilityDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatTokenLogProbabilityDetails chatTokenLogProbabilityDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatTokenLogProbabilityDetails(document.RootElement); + if (chatTokenLogProbabilityDetails == null) + { + return null; + } + return BinaryContent.Create(chatTokenLogProbabilityDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatTokenLogProbabilityDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatTokenLogProbabilityDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatTokenLogProbabilityDetails.cs b/src/Generated/Models/ChatTokenLogProbabilityDetails.cs index 4443ad92e..4c27601ea 100644 --- a/src/Generated/Models/ChatTokenLogProbabilityDetails.cs +++ b/src/Generated/Models/ChatTokenLogProbabilityDetails.cs @@ -10,31 +10,31 @@ namespace OpenAI.Chat { public partial class ChatTokenLogProbabilityDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ChatTokenLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes, IEnumerable topLogProbabilities) { - Argument.AssertNotNull(token, nameof(token)); - Argument.AssertNotNull(topLogProbabilities, nameof(topLogProbabilities)); - Token = token; LogProbability = logProbability; Utf8Bytes = utf8Bytes; TopLogProbabilities = topLogProbabilities.ToList(); } - internal ChatTokenLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes, IReadOnlyList topLogProbabilities, IDictionary serializedAdditionalRawData) + internal ChatTokenLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes, IReadOnlyList topLogProbabilities, IDictionary additionalBinaryDataProperties) { Token = token; LogProbability = logProbability; Utf8Bytes = utf8Bytes; TopLogProbabilities = topLogProbabilities; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatTokenLogProbabilityDetails() + public string Token { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Token { get; } } } diff --git a/src/Generated/Models/ChatTokenTopLogProbabilityDetails.Serialization.cs b/src/Generated/Models/ChatTokenTopLogProbabilityDetails.Serialization.cs index 6f72f1a45..3e4872d39 100644 --- a/src/Generated/Models/ChatTokenTopLogProbabilityDetails.Serialization.cs +++ b/src/Generated/Models/ChatTokenTopLogProbabilityDetails.Serialization.cs @@ -7,37 +7,47 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatTokenTopLogProbabilityDetails : IJsonModel { + internal ChatTokenTopLogProbabilityDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatTokenTopLogProbabilityDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("token") != true) + if (_additionalBinaryDataProperties?.ContainsKey("token") != true) { writer.WritePropertyName("token"u8); writer.WriteStringValue(Token); } - if (SerializedAdditionalRawData?.ContainsKey("logprob") != true) + if (_additionalBinaryDataProperties?.ContainsKey("logprob") != true) { writer.WritePropertyName("logprob"u8); writer.WriteNumberValue(LogProbability); } - if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + if (_additionalBinaryDataProperties?.ContainsKey("bytes") != true) { if (Utf8Bytes != null) { writer.WritePropertyName("bytes"u8); writer.WriteStartArray(); - foreach (var item in Utf8Bytes.Value.Span) + foreach (byte item in Utf8Bytes.Value.Span) { writer.WriteNumberValue(item); } @@ -45,12 +55,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("bytes"); + writer.WriteNull("bytes"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -58,7 +68,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -67,76 +77,72 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - ChatTokenTopLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatTokenTopLogProbabilityDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatTokenTopLogProbabilityDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatTokenTopLogProbabilityDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatTokenTopLogProbabilityDetails(document.RootElement, options); } - internal static ChatTokenTopLogProbabilityDetails DeserializeChatTokenTopLogProbabilityDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatTokenTopLogProbabilityDetails DeserializeChatTokenTopLogProbabilityDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string token = default; - float logprob = default; - ReadOnlyMemory? bytes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float logProbability = default; + ReadOnlyMemory? utf8Bytes = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("token"u8)) + if (prop.NameEquals("token"u8)) { - token = property.Value.GetString(); + token = prop.Value.GetString(); continue; } - if (property.NameEquals("logprob"u8)) + if (prop.NameEquals("logprob"u8)) { - logprob = property.Value.GetSingle(); + logProbability = prop.Value.GetSingle(); continue; } - if (property.NameEquals("bytes"u8)) + if (prop.NameEquals("bytes"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } int index = 0; - byte[] array = new byte[property.Value.GetArrayLength()]; - foreach (var item in property.Value.EnumerateArray()) + byte[] array = new byte[prop.Value.GetArrayLength()]; + foreach (var item in prop.Value.EnumerateArray()) { array[index] = item.GetByte(); index++; } - bytes = new ReadOnlyMemory?(array); + utf8Bytes = new ReadOnlyMemory(array); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatTokenTopLogProbabilityDetails(token, logprob, bytes, serializedAdditionalRawData); + return new ChatTokenTopLogProbabilityDetails(token, logProbability, utf8Bytes, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -146,15 +152,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - ChatTokenTopLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatTokenTopLogProbabilityDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatTokenTopLogProbabilityDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatTokenTopLogProbabilityDetails(document.RootElement, options); } default: @@ -164,15 +171,20 @@ ChatTokenTopLogProbabilityDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatTokenTopLogProbabilityDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatTokenTopLogProbabilityDetails chatTokenTopLogProbabilityDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatTokenTopLogProbabilityDetails(document.RootElement); + if (chatTokenTopLogProbabilityDetails == null) + { + return null; + } + return BinaryContent.Create(chatTokenTopLogProbabilityDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatTokenTopLogProbabilityDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatTokenTopLogProbabilityDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatTokenTopLogProbabilityDetails.cs b/src/Generated/Models/ChatTokenTopLogProbabilityDetails.cs index c02aa387b..97068d2de 100644 --- a/src/Generated/Models/ChatTokenTopLogProbabilityDetails.cs +++ b/src/Generated/Models/ChatTokenTopLogProbabilityDetails.cs @@ -9,28 +9,29 @@ namespace OpenAI.Chat { public partial class ChatTokenTopLogProbabilityDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ChatTokenTopLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes) { - Argument.AssertNotNull(token, nameof(token)); - Token = token; LogProbability = logProbability; Utf8Bytes = utf8Bytes; } - internal ChatTokenTopLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes, IDictionary serializedAdditionalRawData) + internal ChatTokenTopLogProbabilityDetails(string token, float logProbability, ReadOnlyMemory? utf8Bytes, IDictionary additionalBinaryDataProperties) { Token = token; LogProbability = logProbability; Utf8Bytes = utf8Bytes; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatTokenTopLogProbabilityDetails() + public string Token { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Token { get; } } } diff --git a/src/Generated/Models/ChatTokenUsage.Serialization.cs b/src/Generated/Models/ChatTokenUsage.Serialization.cs index 4dbcb7383..d8b52c91e 100644 --- a/src/Generated/Models/ChatTokenUsage.Serialization.cs +++ b/src/Generated/Models/ChatTokenUsage.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatTokenUsage : IJsonModel { + internal ChatTokenUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatTokenUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("completion_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_tokens") != true) { writer.WritePropertyName("completion_tokens"u8); writer.WriteNumberValue(OutputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); writer.WriteNumberValue(InputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("completion_tokens_details") != true && Optional.IsDefined(OutputTokenDetails)) + if (Optional.IsDefined(OutputTokenDetails) && _additionalBinaryDataProperties?.ContainsKey("completion_tokens_details") != true) { writer.WritePropertyName("completion_tokens_details"u8); writer.WriteObjectValue(OutputTokenDetails, options); } - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens_details") != true && Optional.IsDefined(InputTokenDetails)) + if (Optional.IsDefined(InputTokenDetails) && _additionalBinaryDataProperties?.ContainsKey("prompt_tokens_details") != true) { writer.WritePropertyName("prompt_tokens_details"u8); writer.WriteObjectValue(InputTokenDetails, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,91 +75,87 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp #endif } } - writer.WriteEndObject(); } - ChatTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatTokenUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatTokenUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatTokenUsage(document.RootElement, options); } - internal static ChatTokenUsage DeserializeChatTokenUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatTokenUsage DeserializeChatTokenUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int completionTokens = default; - int promptTokens = default; - int totalTokens = default; - ChatOutputTokenUsageDetails completionTokensDetails = default; - ChatInputTokenUsageDetails promptTokensDetails = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int outputTokenCount = default; + int inputTokenCount = default; + int totalTokenCount = default; + ChatOutputTokenUsageDetails outputTokenDetails = default; + ChatInputTokenUsageDetails inputTokenDetails = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("completion_tokens"u8)) + if (prop.NameEquals("completion_tokens"u8)) { - completionTokens = property.Value.GetInt32(); + outputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("prompt_tokens"u8)) + if (prop.NameEquals("prompt_tokens"u8)) { - promptTokens = property.Value.GetInt32(); + inputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("completion_tokens_details"u8)) + if (prop.NameEquals("completion_tokens_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - completionTokensDetails = ChatOutputTokenUsageDetails.DeserializeChatOutputTokenUsageDetails(property.Value, options); + outputTokenDetails = ChatOutputTokenUsageDetails.DeserializeChatOutputTokenUsageDetails(prop.Value, options); continue; } - if (property.NameEquals("prompt_tokens_details"u8)) + if (prop.NameEquals("prompt_tokens_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - promptTokensDetails = ChatInputTokenUsageDetails.DeserializeChatInputTokenUsageDetails(property.Value, options); + inputTokenDetails = ChatInputTokenUsageDetails.DeserializeChatInputTokenUsageDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ChatTokenUsage( - completionTokens, - promptTokens, - totalTokens, - completionTokensDetails, - promptTokensDetails, - serializedAdditionalRawData); + outputTokenCount, + inputTokenCount, + totalTokenCount, + outputTokenDetails, + inputTokenDetails, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -159,15 +165,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - ChatTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatTokenUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatTokenUsage(document.RootElement, options); } default: @@ -177,15 +184,20 @@ ChatTokenUsage IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatTokenUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatTokenUsage chatTokenUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatTokenUsage(document.RootElement); + if (chatTokenUsage == null) + { + return null; + } + return BinaryContent.Create(chatTokenUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatTokenUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatTokenUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatTokenUsage.cs b/src/Generated/Models/ChatTokenUsage.cs index ca981e89f..8e1376866 100644 --- a/src/Generated/Models/ChatTokenUsage.cs +++ b/src/Generated/Models/ChatTokenUsage.cs @@ -9,7 +9,8 @@ namespace OpenAI.Chat { public partial class ChatTokenUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ChatTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount) { OutputTokenCount = outputTokenCount; @@ -17,18 +18,20 @@ internal ChatTokenUsage(int outputTokenCount, int inputTokenCount, int totalToke TotalTokenCount = totalTokenCount; } - internal ChatTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, ChatOutputTokenUsageDetails outputTokenDetails, ChatInputTokenUsageDetails inputTokenDetails, IDictionary serializedAdditionalRawData) + internal ChatTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, ChatOutputTokenUsageDetails outputTokenDetails, ChatInputTokenUsageDetails inputTokenDetails, IDictionary additionalBinaryDataProperties) { OutputTokenCount = outputTokenCount; InputTokenCount = inputTokenCount; TotalTokenCount = totalTokenCount; OutputTokenDetails = outputTokenDetails; InputTokenDetails = inputTokenDetails; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatTokenUsage() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatTool.Serialization.cs b/src/Generated/Models/ChatTool.Serialization.cs index 462a9c65f..42c658144 100644 --- a/src/Generated/Models/ChatTool.Serialization.cs +++ b/src/Generated/Models/ChatTool.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatTool : IJsonModel { + internal ChatTool() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatTool)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions #endif } } - writer.WriteEndObject(); } - ChatTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatTool JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatTool)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatTool(document.RootElement, options); } - internal static ChatTool DeserializeChatTool(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatTool DeserializeChatTool(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ChatToolKind type = default; InternalFunctionDefinition function = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Chat.ChatToolKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("function"u8)) { - type = property.Value.GetString().ToChatToolKind(); + function = InternalFunctionDefinition.DeserializeInternalFunctionDefinition(prop.Value, options); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("type"u8)) { - function = InternalFunctionDefinition.DeserializeInternalFunctionDefinition(property.Value, options); + kind = prop.Value.GetString().ToChatToolKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatTool(type, function, serializedAdditionalRawData); + return new ChatTool(function, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - ChatTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatTool 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatTool(document.RootElement, options); } default: @@ -130,15 +137,20 @@ ChatTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOp string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatTool FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatTool chatTool) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatTool(document.RootElement); + if (chatTool == null) + { + return null; + } + return BinaryContent.Create(chatTool, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatTool(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatTool(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatTool.cs b/src/Generated/Models/ChatTool.cs index d10b8bc5f..2c11930ba 100644 --- a/src/Generated/Models/ChatTool.cs +++ b/src/Generated/Models/ChatTool.cs @@ -4,22 +4,25 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { public partial class ChatTool { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatTool(ChatToolKind kind, InternalFunctionDefinition function, IDictionary serializedAdditionalRawData) + internal ChatTool(InternalFunctionDefinition function, Chat.ChatToolKind kind, IDictionary additionalBinaryDataProperties) { - Kind = kind; Function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatTool() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ChatToolCall.Serialization.cs b/src/Generated/Models/ChatToolCall.Serialization.cs index 19fbfe70d..c7cc7b0e2 100644 --- a/src/Generated/Models/ChatToolCall.Serialization.cs +++ b/src/Generated/Models/ChatToolCall.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatToolCall : IJsonModel { + internal ChatToolCall() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ChatToolCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti #endif } } - writer.WriteEndObject(); } - ChatToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ChatToolCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatToolCall(document.RootElement, options); } - internal static ChatToolCall DeserializeChatToolCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatToolCall DeserializeChatToolCall(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - ChatToolCallKind type = default; InternalChatCompletionMessageToolCallFunction function = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Chat.ChatToolCallKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("function"u8)) { - type = property.Value.GetString().ToChatToolCallKind(); + function = InternalChatCompletionMessageToolCallFunction.DeserializeInternalChatCompletionMessageToolCallFunction(prop.Value, options); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("type"u8)) { - function = InternalChatCompletionMessageToolCallFunction.DeserializeInternalChatCompletionMessageToolCallFunction(property.Value, options); + kind = prop.Value.GetString().ToChatToolCallKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ChatToolCall(id, type, function, serializedAdditionalRawData); + return new ChatToolCall(id, function, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions option } } - ChatToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatToolCall(document.RootElement, options); } default: @@ -141,15 +148,20 @@ ChatToolCall IPersistableModel.Create(BinaryData data, ModelReader string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatToolCall FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatToolCall chatToolCall) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatToolCall(document.RootElement); + if (chatToolCall == null) + { + return null; + } + return BinaryContent.Create(chatToolCall, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatToolCall(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeChatToolCall(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatToolCall.cs b/src/Generated/Models/ChatToolCall.cs index 0d909e905..f4eb9b869 100644 --- a/src/Generated/Models/ChatToolCall.cs +++ b/src/Generated/Models/ChatToolCall.cs @@ -9,20 +9,22 @@ namespace OpenAI.Chat { public partial class ChatToolCall { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ChatToolCall(string id, ChatToolCallKind kind, InternalChatCompletionMessageToolCallFunction function, IDictionary serializedAdditionalRawData) + internal ChatToolCall(string id, InternalChatCompletionMessageToolCallFunction function, Chat.ChatToolCallKind kind, IDictionary additionalBinaryDataProperties) { Id = id; - Kind = kind; Function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ChatToolCall() + public string Id { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Id { get; set; } } } diff --git a/src/Generated/Models/ChatToolCallKind.Serialization.cs b/src/Generated/Models/ChatToolCallKind.Serialization.cs index 3e00876f9..e3711a393 100644 --- a/src/Generated/Models/ChatToolCallKind.Serialization.cs +++ b/src/Generated/Models/ChatToolCallKind.Serialization.cs @@ -8,15 +8,18 @@ namespace OpenAI.Chat { internal static partial class ChatToolCallKindExtensions { - public static string ToSerialString(this ChatToolCallKind value) => value switch + public static string ToSerialString(this Chat.ChatToolCallKind value) => value switch { - ChatToolCallKind.Function => "function", + Chat.ChatToolCallKind.Function => "function", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatToolCallKind value.") }; - public static ChatToolCallKind ToChatToolCallKind(this string value) + public static Chat.ChatToolCallKind ToChatToolCallKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) return ChatToolCallKind.Function; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) + { + return Chat.ChatToolCallKind.Function; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatToolCallKind value."); } } diff --git a/src/Generated/Models/ChatToolChoice.Serialization.cs b/src/Generated/Models/ChatToolChoice.Serialization.cs index 9fd540965..f775a36af 100644 --- a/src/Generated/Models/ChatToolChoice.Serialization.cs +++ b/src/Generated/Models/ChatToolChoice.Serialization.cs @@ -6,27 +6,58 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ChatToolChoice : IJsonModel { - ChatToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ChatToolChoice)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatToolChoice)} does not support writing '{format}' format."); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + ChatToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ChatToolChoice 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(ChatToolChoice)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatToolChoice(document.RootElement, options); + return ChatToolChoice.DeserializeChatToolChoice(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +67,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - ChatToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ChatToolChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeChatToolChoice(document.RootElement, options); + return ChatToolChoice.DeserializeChatToolChoice(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ChatToolChoice)} does not support reading '{options.Format}' format."); @@ -54,15 +86,20 @@ ChatToolChoice IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ChatToolChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ChatToolChoice chatToolChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatToolChoice(document.RootElement); + if (chatToolChoice == null) + { + return null; + } + return BinaryContent.Create(chatToolChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ChatToolChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ChatToolChoice.DeserializeChatToolChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ChatToolChoice.cs b/src/Generated/Models/ChatToolChoice.cs index 5650611aa..6a423d3f8 100644 --- a/src/Generated/Models/ChatToolChoice.cs +++ b/src/Generated/Models/ChatToolChoice.cs @@ -9,6 +9,17 @@ namespace OpenAI.Chat { public partial class ChatToolChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + + internal ChatToolChoice(IDictionary additionalBinaryDataProperties) + { + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ChatToolKind.Serialization.cs b/src/Generated/Models/ChatToolKind.Serialization.cs index 0a04ab836..4191a8230 100644 --- a/src/Generated/Models/ChatToolKind.Serialization.cs +++ b/src/Generated/Models/ChatToolKind.Serialization.cs @@ -8,15 +8,18 @@ namespace OpenAI.Chat { internal static partial class ChatToolKindExtensions { - public static string ToSerialString(this ChatToolKind value) => value switch + public static string ToSerialString(this Chat.ChatToolKind value) => value switch { - ChatToolKind.Function => "function", + Chat.ChatToolKind.Function => "function", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatToolKind value.") }; - public static ChatToolKind ToChatToolKind(this string value) + public static Chat.ChatToolKind ToChatToolKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) return ChatToolKind.Function; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) + { + return Chat.ChatToolKind.Function; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ChatToolKind value."); } } diff --git a/src/Generated/Models/CodeInterpreterToolDefinition.Serialization.cs b/src/Generated/Models/CodeInterpreterToolDefinition.Serialization.cs index c1f2296db..92cb9c4ec 100644 --- a/src/Generated/Models/CodeInterpreterToolDefinition.Serialization.cs +++ b/src/Generated/Models/CodeInterpreterToolDefinition.Serialization.cs @@ -7,55 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class CodeInterpreterToolDefinition : IJsonModel { - CodeInterpreterToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CodeInterpreterToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(CodeInterpreterToolDefinition)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + CodeInterpreterToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (CodeInterpreterToolDefinition)JsonModelCreateCore(ref reader, options); + + protected override ToolDefinition 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(CodeInterpreterToolDefinition)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeCodeInterpreterToolDefinition(document.RootElement, options); } - internal static CodeInterpreterToolDefinition DeserializeCodeInterpreterToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static CodeInterpreterToolDefinition DeserializeCodeInterpreterToolDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "code_interpreter"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new CodeInterpreterToolDefinition(type, serializedAdditionalRawData); + return new CodeInterpreterToolDefinition(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -65,15 +73,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - CodeInterpreterToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + CodeInterpreterToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (CodeInterpreterToolDefinition)PersistableModelCreateCore(data, options); + protected override ToolDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeCodeInterpreterToolDefinition(document.RootElement, options); } default: @@ -83,15 +92,20 @@ CodeInterpreterToolDefinition IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new CodeInterpreterToolDefinition FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(CodeInterpreterToolDefinition codeInterpreterToolDefinition) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeCodeInterpreterToolDefinition(document.RootElement); + if (codeInterpreterToolDefinition == null) + { + return null; + } + return BinaryContent.Create(codeInterpreterToolDefinition, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator CodeInterpreterToolDefinition(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeCodeInterpreterToolDefinition(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/CodeInterpreterToolDefinition.cs b/src/Generated/Models/CodeInterpreterToolDefinition.cs index 1b330ab0d..05f625b85 100644 --- a/src/Generated/Models/CodeInterpreterToolDefinition.cs +++ b/src/Generated/Models/CodeInterpreterToolDefinition.cs @@ -9,12 +9,11 @@ namespace OpenAI.Assistants { public partial class CodeInterpreterToolDefinition : ToolDefinition { - public CodeInterpreterToolDefinition() + public CodeInterpreterToolDefinition() : base("code_interpreter") { - Type = "code_interpreter"; } - internal CodeInterpreterToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal CodeInterpreterToolDefinition(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/CodeInterpreterToolResources.Serialization.cs b/src/Generated/Models/CodeInterpreterToolResources.Serialization.cs index 467dad787..6798b11b8 100644 --- a/src/Generated/Models/CodeInterpreterToolResources.Serialization.cs +++ b/src/Generated/Models/CodeInterpreterToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ public partial class CodeInterpreterToolResources : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(CodeInterpreterToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - CodeInterpreterToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + CodeInterpreterToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual CodeInterpreterToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(CodeInterpreterToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeCodeInterpreterToolResources(document.RootElement, options); } - internal static CodeInterpreterToolResources DeserializeCodeInterpreterToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static CodeInterpreterToolResources DeserializeCodeInterpreterToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new CodeInterpreterToolResources(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new CodeInterpreterToolResources(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - CodeInterpreterToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + CodeInterpreterToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual CodeInterpreterToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeCodeInterpreterToolResources(document.RootElement, options); } default: @@ -133,15 +148,20 @@ CodeInterpreterToolResources IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static CodeInterpreterToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(CodeInterpreterToolResources codeInterpreterToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeCodeInterpreterToolResources(document.RootElement); + if (codeInterpreterToolResources == null) + { + return null; + } + return BinaryContent.Create(codeInterpreterToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator CodeInterpreterToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeCodeInterpreterToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/CodeInterpreterToolResources.cs b/src/Generated/Models/CodeInterpreterToolResources.cs index 1735ff0f9..5eedc9577 100644 --- a/src/Generated/Models/CodeInterpreterToolResources.cs +++ b/src/Generated/Models/CodeInterpreterToolResources.cs @@ -9,12 +9,18 @@ namespace OpenAI.Assistants { public partial class CodeInterpreterToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal CodeInterpreterToolResources(IList fileIds, IDictionary serializedAdditionalRawData) + internal CodeInterpreterToolResources(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ConversationAudioFormat.cs b/src/Generated/Models/ConversationAudioFormat.cs index 0af6d2cbd..110006816 100644 --- a/src/Generated/Models/ConversationAudioFormat.cs +++ b/src/Generated/Models/ConversationAudioFormat.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationAudioFormat : IEquatable { private readonly string _value; + private const string Pcm16Value = "pcm16"; + private const string G711UlawValue = "g711_ulaw"; + private const string G711AlawValue = "g711_alaw"; public ConversationAudioFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Pcm16Value = "pcm16"; - private const string G711UlawValue = "g711_ulaw"; - private const string G711AlawValue = "g711_alaw"; + _value = value; + } public static ConversationAudioFormat Pcm16 { get; } = new ConversationAudioFormat(Pcm16Value); + public static ConversationAudioFormat G711Ulaw { get; } = new ConversationAudioFormat(G711UlawValue); + public static ConversationAudioFormat G711Alaw { get; } = new ConversationAudioFormat(G711AlawValue); + public static bool operator ==(ConversationAudioFormat left, ConversationAudioFormat right) => left.Equals(right); + public static bool operator !=(ConversationAudioFormat left, ConversationAudioFormat right) => !left.Equals(right); + public static implicit operator ConversationAudioFormat(string value) => new ConversationAudioFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationAudioFormat other && Equals(other); + public bool Equals(ConversationAudioFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationContentPart.Serialization.cs b/src/Generated/Models/ConversationContentPart.Serialization.cs index d499c65d4..76066d621 100644 --- a/src/Generated/Models/ConversationContentPart.Serialization.cs +++ b/src/Generated/Models/ConversationContentPart.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeContentPart))] - public partial class ConversationContentPart : IJsonModel + public abstract partial class ConversationContentPart : IJsonModel { + internal ConversationContentPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Kind.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,46 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - ConversationContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationContentPart(document.RootElement, options); } - internal static ConversationContentPart DeserializeConversationContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationContentPart DeserializeConversationContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "audio": return InternalRealtimeResponseAudioContentPart.DeserializeInternalRealtimeResponseAudioContentPart(element, options); - case "input_audio": return InternalRealtimeRequestAudioContentPart.DeserializeInternalRealtimeRequestAudioContentPart(element, options); - case "input_text": return InternalRealtimeRequestTextContentPart.DeserializeInternalRealtimeRequestTextContentPart(element, options); - case "text": return InternalRealtimeResponseTextContentPart.DeserializeInternalRealtimeResponseTextContentPart(element, options); + case "input_text": + return InternalRealtimeRequestTextContentPart.DeserializeInternalRealtimeRequestTextContentPart(element, options); + case "input_audio": + return InternalRealtimeRequestAudioContentPart.DeserializeInternalRealtimeRequestAudioContentPart(element, options); + case "text": + return InternalRealtimeResponseTextContentPart.DeserializeInternalRealtimeResponseTextContentPart(element, options); + case "audio": + return InternalRealtimeResponseAudioContentPart.DeserializeInternalRealtimeResponseAudioContentPart(element, options); } } return UnknownRealtimeContentPart.DeserializeUnknownRealtimeContentPart(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -94,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - ConversationContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationContentPart(document.RootElement, options); } default: @@ -112,15 +126,20 @@ ConversationContentPart IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationContentPart conversationContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationContentPart(document.RootElement); + if (conversationContentPart == null) + { + return null; + } + return BinaryContent.Create(conversationContentPart, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationContentPart.cs b/src/Generated/Models/ConversationContentPart.cs index 868e21f83..fe35eb936 100644 --- a/src/Generated/Models/ConversationContentPart.cs +++ b/src/Generated/Models/ConversationContentPart.cs @@ -9,17 +9,25 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationContentPart { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationContentPart() + private protected IDictionary _additionalBinaryDataProperties; + + private protected ConversationContentPart(ConversationContentPartKind kind) { + Kind = kind; } - internal ConversationContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData) + internal ConversationContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties) { Kind = kind; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal ConversationContentPartKind Kind { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationContentPartKind.cs b/src/Generated/Models/ConversationContentPartKind.cs index 97c714033..a754da730 100644 --- a/src/Generated/Models/ConversationContentPartKind.cs +++ b/src/Generated/Models/ConversationContentPartKind.cs @@ -4,35 +4,43 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationContentPartKind : IEquatable { private readonly string _value; + private const string InputTextValue = "input_text"; + private const string InputAudioValue = "input_audio"; + private const string TextValue = "text"; + private const string AudioValue = "audio"; public ConversationContentPartKind(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string InputTextValue = "input_text"; - private const string InputAudioValue = "input_audio"; - private const string OutputTextValue = "text"; - private const string OutputAudioValue = "audio"; + _value = value; + } public static ConversationContentPartKind InputText { get; } = new ConversationContentPartKind(InputTextValue); + public static ConversationContentPartKind InputAudio { get; } = new ConversationContentPartKind(InputAudioValue); + public static bool operator ==(ConversationContentPartKind left, ConversationContentPartKind right) => left.Equals(right); + public static bool operator !=(ConversationContentPartKind left, ConversationContentPartKind right) => !left.Equals(right); + public static implicit operator ConversationContentPartKind(string value) => new ConversationContentPartKind(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationContentPartKind other && Equals(other); + public bool Equals(ConversationContentPartKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationErrorUpdate.Serialization.cs b/src/Generated/Models/ConversationErrorUpdate.Serialization.cs index 6c8d27e98..2dc634db0 100644 --- a/src/Generated/Models/ConversationErrorUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationErrorUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationErrorUpdate : IJsonModel { + internal ConversationErrorUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationErrorUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("error") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("error") != true) { writer.WritePropertyName("error"u8); writer.WriteObjectValue(_error, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationErrorUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationErrorUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationErrorUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationErrorUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationErrorUpdate(document.RootElement, options); } - internal static ConversationErrorUpdate DeserializeConversationErrorUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationErrorUpdate DeserializeConversationErrorUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeServerEventErrorError error = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeServerEventErrorError error = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("error"u8)) + if (prop.NameEquals("event_id"u8)) { - error = InternalRealtimeServerEventErrorError.DeserializeInternalRealtimeServerEventErrorError(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("error"u8)) { - eventId = property.Value.GetString(); + error = InternalRealtimeServerEventErrorError.DeserializeInternalRealtimeServerEventErrorError(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationErrorUpdate(type, eventId, serializedAdditionalRawData, error); + return new ConversationErrorUpdate(eventId, kind, additionalBinaryDataProperties, error); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - ConversationErrorUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationErrorUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationErrorUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationErrorUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationErrorUpdate IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationErrorUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationErrorUpdate conversationErrorUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationErrorUpdate(document.RootElement); + if (conversationErrorUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationErrorUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationErrorUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationErrorUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationErrorUpdate.cs b/src/Generated/Models/ConversationErrorUpdate.cs index 861ce8204..706445488 100644 --- a/src/Generated/Models/ConversationErrorUpdate.cs +++ b/src/Generated/Models/ConversationErrorUpdate.cs @@ -9,22 +9,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationErrorUpdate : ConversationUpdate { - internal ConversationErrorUpdate(string eventId, InternalRealtimeServerEventErrorError error) : base(eventId) + internal ConversationErrorUpdate(string eventId, InternalRealtimeServerEventErrorError error) : base(eventId, RealtimeConversation.ConversationUpdateKind.Error) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(error, nameof(error)); - - Kind = ConversationUpdateKind.Error; _error = error; } - internal ConversationErrorUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeServerEventErrorError error) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationErrorUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeServerEventErrorError error) : base(eventId, kind, additionalBinaryDataProperties) { _error = error; } - - internal ConversationErrorUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationFunctionTool.Serialization.cs b/src/Generated/Models/ConversationFunctionTool.Serialization.cs index 8f7408123..430145248 100644 --- a/src/Generated/Models/ConversationFunctionTool.Serialization.cs +++ b/src/Generated/Models/ConversationFunctionTool.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,28 +15,34 @@ public partial class ConversationFunctionTool : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationFunctionTool)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(_name); } - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(_description)) + if (Optional.IsDefined(_description) && _additionalBinaryDataProperties?.ContainsKey("description") != true) { writer.WritePropertyName("description"u8); writer.WriteStringValue(_description); } - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true && Optional.IsDefined(_parameters)) + if (Optional.IsDefined(_parameters) && _additionalBinaryDataProperties?.ContainsKey("parameters") != true) { writer.WritePropertyName("parameters"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(_parameters); + writer.WriteRawValue(_parameters); #else using (JsonDocument document = JsonDocument.Parse(_parameters)) { @@ -43,99 +50,71 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } #endif } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationFunctionTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationFunctionTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationFunctionTool)JsonModelCreateCore(ref reader, options); + + protected override ConversationTool JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationFunctionTool)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationFunctionTool(document.RootElement, options); } - internal static ConversationFunctionTool DeserializeConversationFunctionTool(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationFunctionTool DeserializeConversationFunctionTool(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + ConversationToolKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string name = default; string description = default; BinaryData parameters = default; - ConversationToolKind type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("type"u8)) { - name = property.Value.GetString(); + kind = new ConversationToolKind(prop.Value.GetString()); continue; } - if (property.NameEquals("description"u8)) + if (prop.NameEquals("name"u8)) { - description = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("parameters"u8)) + if (prop.NameEquals("description"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parameters = BinaryData.FromString(property.Value.GetRawText()); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("parameters"u8)) { - type = new ConversationToolKind(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parameters = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationFunctionTool(type, serializedAdditionalRawData, name, description, parameters); + return new ConversationFunctionTool(kind, additionalBinaryDataProperties, name, description, parameters); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -145,15 +124,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - ConversationFunctionTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationFunctionTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationFunctionTool)PersistableModelCreateCore(data, options); + protected override ConversationTool 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationFunctionTool(document.RootElement, options); } default: @@ -163,15 +143,20 @@ ConversationFunctionTool IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationFunctionTool FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationFunctionTool conversationFunctionTool) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationFunctionTool(document.RootElement); + if (conversationFunctionTool == null) + { + return null; + } + return BinaryContent.Create(conversationFunctionTool, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationFunctionTool(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationFunctionTool(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationFunctionTool.cs b/src/Generated/Models/ConversationFunctionTool.cs index e8fd7186c..cf6dc64bb 100644 --- a/src/Generated/Models/ConversationFunctionTool.cs +++ b/src/Generated/Models/ConversationFunctionTool.cs @@ -2,9 +2,6 @@ #nullable disable -using System; -using System.Collections.Generic; - namespace OpenAI.RealtimeConversation { public partial class ConversationFunctionTool : ConversationTool diff --git a/src/Generated/Models/ConversationInputAudioClearedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputAudioClearedUpdate.Serialization.cs index e88bfd7c1..2ea91978a 100644 --- a/src/Generated/Models/ConversationInputAudioClearedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputAudioClearedUpdate.Serialization.cs @@ -7,102 +7,80 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputAudioClearedUpdate : IJsonModel { + internal ConversationInputAudioClearedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputAudioClearedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationInputAudioClearedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputAudioClearedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputAudioClearedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputAudioClearedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputAudioClearedUpdate(document.RootElement, options); } - internal static ConversationInputAudioClearedUpdate DeserializeConversationInputAudioClearedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputAudioClearedUpdate DeserializeConversationInputAudioClearedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("type"u8)) { - eventId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputAudioClearedUpdate(type, eventId, serializedAdditionalRawData); + return new ConversationInputAudioClearedUpdate(eventId, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +90,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - ConversationInputAudioClearedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputAudioClearedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputAudioClearedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputAudioClearedUpdate(document.RootElement, options); } default: @@ -130,15 +109,20 @@ ConversationInputAudioClearedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputAudioClearedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputAudioClearedUpdate conversationInputAudioClearedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputAudioClearedUpdate(document.RootElement); + if (conversationInputAudioClearedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputAudioClearedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputAudioClearedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputAudioClearedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputAudioClearedUpdate.cs b/src/Generated/Models/ConversationInputAudioClearedUpdate.cs index 69c9b597c..ce6fc9d78 100644 --- a/src/Generated/Models/ConversationInputAudioClearedUpdate.cs +++ b/src/Generated/Models/ConversationInputAudioClearedUpdate.cs @@ -9,18 +9,11 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputAudioClearedUpdate : ConversationUpdate { - internal ConversationInputAudioClearedUpdate(string eventId) : base(eventId) - { - Argument.AssertNotNull(eventId, nameof(eventId)); - - Kind = ConversationUpdateKind.InputAudioCleared; - } - - internal ConversationInputAudioClearedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputAudioClearedUpdate(string eventId) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputAudioCleared) { } - internal ConversationInputAudioClearedUpdate() + internal ConversationInputAudioClearedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties) : base(eventId, kind, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/ConversationInputAudioCommittedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputAudioCommittedUpdate.Serialization.cs index 6a3da8605..f111f6e0c 100644 --- a/src/Generated/Models/ConversationInputAudioCommittedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputAudioCommittedUpdate.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputAudioCommittedUpdate : IJsonModel { + internal ConversationInputAudioCommittedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputAudioCommittedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("previous_item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("previous_item_id") != true) { writer.WritePropertyName("previous_item_id"u8); writer.WriteStringValue(PreviousItemId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationInputAudioCommittedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputAudioCommittedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputAudioCommittedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputAudioCommittedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputAudioCommittedUpdate(document.RootElement, options); } - internal static ConversationInputAudioCommittedUpdate DeserializeConversationInputAudioCommittedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputAudioCommittedUpdate DeserializeConversationInputAudioCommittedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string previousItemId = default; string itemId = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("previous_item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - previousItemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("previous_item_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + previousItemId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item_id"u8)) { - eventId = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputAudioCommittedUpdate(type, eventId, serializedAdditionalRawData, previousItemId, itemId); + return new ConversationInputAudioCommittedUpdate(eventId, kind, additionalBinaryDataProperties, previousItemId, itemId); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel.Write(ModelR } } - ConversationInputAudioCommittedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputAudioCommittedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputAudioCommittedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputAudioCommittedUpdate(document.RootElement, options); } default: @@ -152,15 +131,20 @@ ConversationInputAudioCommittedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputAudioCommittedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputAudioCommittedUpdate conversationInputAudioCommittedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputAudioCommittedUpdate(document.RootElement); + if (conversationInputAudioCommittedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputAudioCommittedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputAudioCommittedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputAudioCommittedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputAudioCommittedUpdate.cs b/src/Generated/Models/ConversationInputAudioCommittedUpdate.cs index a7ba4389e..7368ff34e 100644 --- a/src/Generated/Models/ConversationInputAudioCommittedUpdate.cs +++ b/src/Generated/Models/ConversationInputAudioCommittedUpdate.cs @@ -9,28 +9,20 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputAudioCommittedUpdate : ConversationUpdate { - internal ConversationInputAudioCommittedUpdate(string eventId, string previousItemId, string itemId) : base(eventId) + internal ConversationInputAudioCommittedUpdate(string eventId, string previousItemId, string itemId) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputAudioCommitted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(previousItemId, nameof(previousItemId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.InputAudioCommitted; PreviousItemId = previousItemId; ItemId = itemId; } - internal ConversationInputAudioCommittedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string previousItemId, string itemId) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputAudioCommittedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string previousItemId, string itemId) : base(eventId, kind, additionalBinaryDataProperties) { PreviousItemId = previousItemId; ItemId = itemId; } - internal ConversationInputAudioCommittedUpdate() - { - } - public string PreviousItemId { get; } + public string ItemId { get; } } } diff --git a/src/Generated/Models/ConversationInputSpeechFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputSpeechFinishedUpdate.Serialization.cs index 2d5d424bb..3a8e0872c 100644 --- a/src/Generated/Models/ConversationInputSpeechFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputSpeechFinishedUpdate.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputSpeechFinishedUpdate : IJsonModel { + internal ConversationInputSpeechFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputSpeechFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("audio_end_ms") != true) - { - writer.WritePropertyName("audio_end_ms"u8); - writer.WriteNumberValue(_audioEndMs); - } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_end_ms") != true) { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } + writer.WritePropertyName("audio_end_ms"u8); + writer.WriteNumberValue(_audioEndMs); } - writer.WriteEndObject(); } - ConversationInputSpeechFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputSpeechFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputSpeechFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputSpeechFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputSpeechFinishedUpdate(document.RootElement, options); } - internal static ConversationInputSpeechFinishedUpdate DeserializeConversationInputSpeechFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputSpeechFinishedUpdate DeserializeConversationInputSpeechFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int audioEndMs = default; - string itemId = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string itemId = default; + int audioEndMs = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("audio_end_ms"u8)) + if (prop.NameEquals("event_id"u8)) { - audioEndMs = property.Value.GetInt32(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("item_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("audio_end_ms"u8)) { - eventId = property.Value.GetString(); + audioEndMs = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputSpeechFinishedUpdate(type, eventId, serializedAdditionalRawData, audioEndMs, itemId); + return new ConversationInputSpeechFinishedUpdate(eventId, kind, additionalBinaryDataProperties, itemId, audioEndMs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel.Write(ModelR } } - ConversationInputSpeechFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputSpeechFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputSpeechFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputSpeechFinishedUpdate(document.RootElement, options); } default: @@ -152,15 +131,20 @@ ConversationInputSpeechFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputSpeechFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputSpeechFinishedUpdate conversationInputSpeechFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputSpeechFinishedUpdate(document.RootElement); + if (conversationInputSpeechFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputSpeechFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputSpeechFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputSpeechFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputSpeechFinishedUpdate.cs b/src/Generated/Models/ConversationInputSpeechFinishedUpdate.cs index e1698b3af..34f97eeca 100644 --- a/src/Generated/Models/ConversationInputSpeechFinishedUpdate.cs +++ b/src/Generated/Models/ConversationInputSpeechFinishedUpdate.cs @@ -9,25 +9,18 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputSpeechFinishedUpdate : ConversationUpdate { - internal ConversationInputSpeechFinishedUpdate(string eventId, int audioEndMs, string itemId) : base(eventId) + internal ConversationInputSpeechFinishedUpdate(string eventId, string itemId, int audioEndMs) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputSpeechStopped) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.InputSpeechStopped; - _audioEndMs = audioEndMs; ItemId = itemId; + _audioEndMs = audioEndMs; } - internal ConversationInputSpeechFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, int audioEndMs, string itemId) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputSpeechFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId, int audioEndMs) : base(eventId, kind, additionalBinaryDataProperties) { - _audioEndMs = audioEndMs; ItemId = itemId; + _audioEndMs = audioEndMs; } - internal ConversationInputSpeechFinishedUpdate() - { - } public string ItemId { get; } } } diff --git a/src/Generated/Models/ConversationInputSpeechStartedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputSpeechStartedUpdate.Serialization.cs index 6d9913523..69ec19c46 100644 --- a/src/Generated/Models/ConversationInputSpeechStartedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputSpeechStartedUpdate.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputSpeechStartedUpdate : IJsonModel { + internal ConversationInputSpeechStartedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputSpeechStartedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("audio_start_ms") != true) - { - writer.WritePropertyName("audio_start_ms"u8); - writer.WriteNumberValue(_audioStartMs); - } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_start_ms") != true) { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } + writer.WritePropertyName("audio_start_ms"u8); + writer.WriteNumberValue(_audioStartMs); } - writer.WriteEndObject(); } - ConversationInputSpeechStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputSpeechStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputSpeechStartedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputSpeechStartedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputSpeechStartedUpdate(document.RootElement, options); } - internal static ConversationInputSpeechStartedUpdate DeserializeConversationInputSpeechStartedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputSpeechStartedUpdate DeserializeConversationInputSpeechStartedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int audioStartMs = default; - string itemId = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string itemId = default; + int audioStartMs = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("audio_start_ms"u8)) + if (prop.NameEquals("event_id"u8)) { - audioStartMs = property.Value.GetInt32(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("item_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("audio_start_ms"u8)) { - eventId = property.Value.GetString(); + audioStartMs = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputSpeechStartedUpdate(type, eventId, serializedAdditionalRawData, audioStartMs, itemId); + return new ConversationInputSpeechStartedUpdate(eventId, kind, additionalBinaryDataProperties, itemId, audioStartMs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - ConversationInputSpeechStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputSpeechStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputSpeechStartedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputSpeechStartedUpdate(document.RootElement, options); } default: @@ -152,15 +131,20 @@ ConversationInputSpeechStartedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputSpeechStartedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputSpeechStartedUpdate conversationInputSpeechStartedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputSpeechStartedUpdate(document.RootElement); + if (conversationInputSpeechStartedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputSpeechStartedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputSpeechStartedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputSpeechStartedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputSpeechStartedUpdate.cs b/src/Generated/Models/ConversationInputSpeechStartedUpdate.cs index 361347232..3c66eb859 100644 --- a/src/Generated/Models/ConversationInputSpeechStartedUpdate.cs +++ b/src/Generated/Models/ConversationInputSpeechStartedUpdate.cs @@ -9,25 +9,18 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputSpeechStartedUpdate : ConversationUpdate { - internal ConversationInputSpeechStartedUpdate(string eventId, int audioStartMs, string itemId) : base(eventId) + internal ConversationInputSpeechStartedUpdate(string eventId, string itemId, int audioStartMs) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputSpeechStarted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.InputSpeechStarted; - _audioStartMs = audioStartMs; ItemId = itemId; + _audioStartMs = audioStartMs; } - internal ConversationInputSpeechStartedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, int audioStartMs, string itemId) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputSpeechStartedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId, int audioStartMs) : base(eventId, kind, additionalBinaryDataProperties) { - _audioStartMs = audioStartMs; ItemId = itemId; + _audioStartMs = audioStartMs; } - internal ConversationInputSpeechStartedUpdate() - { - } public string ItemId { get; } } } diff --git a/src/Generated/Models/ConversationInputTokenUsageDetails.Serialization.cs b/src/Generated/Models/ConversationInputTokenUsageDetails.Serialization.cs index f4a29a5b6..ca18ed51e 100644 --- a/src/Generated/Models/ConversationInputTokenUsageDetails.Serialization.cs +++ b/src/Generated/Models/ConversationInputTokenUsageDetails.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputTokenUsageDetails : IJsonModel { + internal ConversationInputTokenUsageDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputTokenUsageDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("cached_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cached_tokens") != true) { writer.WritePropertyName("cached_tokens"u8); writer.WriteNumberValue(CachedTokens); } - if (SerializedAdditionalRawData?.ContainsKey("text_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text_tokens") != true) { writer.WritePropertyName("text_tokens"u8); writer.WriteNumberValue(TextTokens); } - if (SerializedAdditionalRawData?.ContainsKey("audio_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_tokens") != true) { writer.WritePropertyName("audio_tokens"u8); writer.WriteNumberValue(AudioTokens); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,25 +65,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - ConversationInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationInputTokenUsageDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputTokenUsageDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputTokenUsageDetails(document.RootElement, options); } - internal static ConversationInputTokenUsageDetails DeserializeConversationInputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputTokenUsageDetails DeserializeConversationInputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -81,39 +89,37 @@ internal static ConversationInputTokenUsageDetails DeserializeConversationInputT int cachedTokens = default; int textTokens = default; int audioTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("cached_tokens"u8)) + if (prop.NameEquals("cached_tokens"u8)) { - cachedTokens = property.Value.GetInt32(); + cachedTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("text_tokens"u8)) + if (prop.NameEquals("text_tokens"u8)) { - textTokens = property.Value.GetInt32(); + textTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("audio_tokens"u8)) + if (prop.NameEquals("audio_tokens"u8)) { - audioTokens = property.Value.GetInt32(); + audioTokens = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputTokenUsageDetails(cachedTokens, textTokens, audioTokens, serializedAdditionalRawData); + return new ConversationInputTokenUsageDetails(cachedTokens, textTokens, audioTokens, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - ConversationInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationInputTokenUsageDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputTokenUsageDetails(document.RootElement, options); } default: @@ -141,15 +148,20 @@ ConversationInputTokenUsageDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationInputTokenUsageDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputTokenUsageDetails conversationInputTokenUsageDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputTokenUsageDetails(document.RootElement); + if (conversationInputTokenUsageDetails == null) + { + return null; + } + return BinaryContent.Create(conversationInputTokenUsageDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationInputTokenUsageDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputTokenUsageDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputTokenUsageDetails.cs b/src/Generated/Models/ConversationInputTokenUsageDetails.cs index 72bee755f..d22b0020a 100644 --- a/src/Generated/Models/ConversationInputTokenUsageDetails.cs +++ b/src/Generated/Models/ConversationInputTokenUsageDetails.cs @@ -9,7 +9,8 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputTokenUsageDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ConversationInputTokenUsageDetails(int cachedTokens, int textTokens, int audioTokens) { CachedTokens = cachedTokens; @@ -17,20 +18,24 @@ internal ConversationInputTokenUsageDetails(int cachedTokens, int textTokens, in AudioTokens = audioTokens; } - internal ConversationInputTokenUsageDetails(int cachedTokens, int textTokens, int audioTokens, IDictionary serializedAdditionalRawData) + internal ConversationInputTokenUsageDetails(int cachedTokens, int textTokens, int audioTokens, IDictionary additionalBinaryDataProperties) { CachedTokens = cachedTokens; TextTokens = textTokens; AudioTokens = audioTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ConversationInputTokenUsageDetails() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int CachedTokens { get; } + public int TextTokens { get; } + public int AudioTokens { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.Serialization.cs index 35fbb1c8c..885a53b40 100644 --- a/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputTranscriptionFailedUpdate : IJsonModel { + internal ConversationInputTranscriptionFailedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputTranscriptionFailedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("error") != true) { writer.WritePropertyName("error"u8); writer.WriteObjectValue(_error, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationInputTranscriptionFailedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputTranscriptionFailedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputTranscriptionFailedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputTranscriptionFailedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputTranscriptionFailedUpdate(document.RootElement, options); } - internal static ConversationInputTranscriptionFailedUpdate DeserializeConversationInputTranscriptionFailedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputTranscriptionFailedUpdate DeserializeConversationInputTranscriptionFailedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string itemId = default; int contentIndex = default; InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - itemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("type"u8)) { - contentIndex = property.Value.GetInt32(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("error"u8)) + if (prop.NameEquals("item_id"u8)) { - error = InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(property.Value, options); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("error"u8)) { - eventId = property.Value.GetString(); + error = InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationInputTranscriptionFailedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, itemId, contentIndex, error); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Write(M } } - ConversationInputTranscriptionFailedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputTranscriptionFailedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputTranscriptionFailedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputTranscriptionFailedUpdate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ ConversationInputTranscriptionFailedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputTranscriptionFailedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputTranscriptionFailedUpdate conversationInputTranscriptionFailedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputTranscriptionFailedUpdate(document.RootElement); + if (conversationInputTranscriptionFailedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputTranscriptionFailedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputTranscriptionFailedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputTranscriptionFailedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.cs b/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.cs index eed7cccb0..e9d2017ac 100644 --- a/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.cs +++ b/src/Generated/Models/ConversationInputTranscriptionFailedUpdate.cs @@ -9,30 +9,22 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputTranscriptionFailedUpdate : ConversationUpdate { - internal ConversationInputTranscriptionFailedUpdate(string eventId, string itemId, int contentIndex, InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error) : base(eventId) + internal ConversationInputTranscriptionFailedUpdate(string eventId, string itemId, int contentIndex, InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputTranscriptionFailed) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(error, nameof(error)); - - Kind = ConversationUpdateKind.InputTranscriptionFailed; ItemId = itemId; ContentIndex = contentIndex; _error = error; } - internal ConversationInputTranscriptionFailedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string itemId, int contentIndex, InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputTranscriptionFailedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId, int contentIndex, InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error) : base(eventId, kind, additionalBinaryDataProperties) { ItemId = itemId; ContentIndex = contentIndex; _error = error; } - internal ConversationInputTranscriptionFailedUpdate() - { - } - public string ItemId { get; } + public int ContentIndex { get; } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.Serialization.cs index 7459b3fad..03a517a46 100644 --- a/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationInputTranscriptionFinishedUpdate : IJsonModel { + internal ConversationInputTranscriptionFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputTranscriptionFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("transcript") != true) + if (_additionalBinaryDataProperties?.ContainsKey("transcript") != true) { writer.WritePropertyName("transcript"u8); writer.WriteStringValue(Transcript); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationInputTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationInputTranscriptionFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputTranscriptionFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputTranscriptionFinishedUpdate(document.RootElement, options); } - internal static ConversationInputTranscriptionFinishedUpdate DeserializeConversationInputTranscriptionFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputTranscriptionFinishedUpdate DeserializeConversationInputTranscriptionFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string itemId = default; int contentIndex = default; string transcript = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - itemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("type"u8)) { - contentIndex = property.Value.GetInt32(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("transcript"u8)) + if (prop.NameEquals("item_id"u8)) { - transcript = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("transcript"u8)) { - eventId = property.Value.GetString(); + transcript = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationInputTranscriptionFinishedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, itemId, contentIndex, transcript); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Write } } - ConversationInputTranscriptionFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputTranscriptionFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationInputTranscriptionFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputTranscriptionFinishedUpdate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ ConversationInputTranscriptionFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationInputTranscriptionFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputTranscriptionFinishedUpdate conversationInputTranscriptionFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputTranscriptionFinishedUpdate(document.RootElement); + if (conversationInputTranscriptionFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationInputTranscriptionFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationInputTranscriptionFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputTranscriptionFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.cs b/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.cs index 3c840f8f5..d96e14344 100644 --- a/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.cs +++ b/src/Generated/Models/ConversationInputTranscriptionFinishedUpdate.cs @@ -9,31 +9,24 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputTranscriptionFinishedUpdate : ConversationUpdate { - internal ConversationInputTranscriptionFinishedUpdate(string eventId, string itemId, int contentIndex, string transcript) : base(eventId) + internal ConversationInputTranscriptionFinishedUpdate(string eventId, string itemId, int contentIndex, string transcript) : base(eventId, RealtimeConversation.ConversationUpdateKind.InputTranscriptionFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(transcript, nameof(transcript)); - - Kind = ConversationUpdateKind.InputTranscriptionFinished; ItemId = itemId; ContentIndex = contentIndex; Transcript = transcript; } - internal ConversationInputTranscriptionFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string itemId, int contentIndex, string transcript) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationInputTranscriptionFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId, int contentIndex, string transcript) : base(eventId, kind, additionalBinaryDataProperties) { ItemId = itemId; ContentIndex = contentIndex; Transcript = transcript; } - internal ConversationInputTranscriptionFinishedUpdate() - { - } - public string ItemId { get; } + public int ContentIndex { get; } + public string Transcript { get; } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionOptions.Serialization.cs b/src/Generated/Models/ConversationInputTranscriptionOptions.Serialization.cs index d16f29d9d..a6183f7b6 100644 --- a/src/Generated/Models/ConversationInputTranscriptionOptions.Serialization.cs +++ b/src/Generated/Models/ConversationInputTranscriptionOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,21 +15,26 @@ public partial class ConversationInputTranscriptionOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationInputTranscriptionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.Value.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,57 +51,53 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - ConversationInputTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationInputTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationInputTranscriptionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationInputTranscriptionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationInputTranscriptionOptions(document.RootElement, options); } - internal static ConversationInputTranscriptionOptions DeserializeConversationInputTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationInputTranscriptionOptions DeserializeConversationInputTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } ConversationTranscriptionModel? model = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - model = new ConversationTranscriptionModel(property.Value.GetString()); + model = new ConversationTranscriptionModel(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationInputTranscriptionOptions(model, serializedAdditionalRawData); + return new ConversationInputTranscriptionOptions(model, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -105,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelR } } - ConversationInputTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationInputTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationInputTranscriptionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationInputTranscriptionOptions(document.RootElement, options); } default: @@ -123,15 +126,20 @@ ConversationInputTranscriptionOptions IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationInputTranscriptionOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationInputTranscriptionOptions conversationInputTranscriptionOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationInputTranscriptionOptions(document.RootElement); + if (conversationInputTranscriptionOptions == null) + { + return null; + } + return BinaryContent.Create(conversationInputTranscriptionOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationInputTranscriptionOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationInputTranscriptionOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationInputTranscriptionOptions.cs b/src/Generated/Models/ConversationInputTranscriptionOptions.cs index 33797601d..8e3d8e35a 100644 --- a/src/Generated/Models/ConversationInputTranscriptionOptions.cs +++ b/src/Generated/Models/ConversationInputTranscriptionOptions.cs @@ -9,17 +9,24 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationInputTranscriptionOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ConversationInputTranscriptionOptions() { } - internal ConversationInputTranscriptionOptions(ConversationTranscriptionModel? model, IDictionary serializedAdditionalRawData) + internal ConversationInputTranscriptionOptions(ConversationTranscriptionModel? model, IDictionary additionalBinaryDataProperties) { Model = model; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public ConversationTranscriptionModel? Model { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationItem.Serialization.cs b/src/Generated/Models/ConversationItem.Serialization.cs index 91a947606..111d83747 100644 --- a/src/Generated/Models/ConversationItem.Serialization.cs +++ b/src/Generated/Models/ConversationItem.Serialization.cs @@ -6,34 +6,44 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeRequestItem))] - public partial class ConversationItem : IJsonModel + public abstract partial class ConversationItem : IJsonModel { + internal ConversationItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,48 +60,47 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - ConversationItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItem(document.RootElement, options); } - internal static ConversationItem DeserializeConversationItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItem DeserializeConversationItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "assistant": return InternalRealtimeRequestAssistantMessageItem.DeserializeInternalRealtimeRequestAssistantMessageItem(element, options); - case "function_call": return InternalRealtimeRequestFunctionCallItem.DeserializeInternalRealtimeRequestFunctionCallItem(element, options); - case "function_call_output": return InternalRealtimeRequestFunctionCallOutputItem.DeserializeInternalRealtimeRequestFunctionCallOutputItem(element, options); - case "message": return InternalRealtimeRequestMessageItem.DeserializeInternalRealtimeRequestMessageItem(element, options); - case "system": return InternalRealtimeRequestSystemMessageItem.DeserializeInternalRealtimeRequestSystemMessageItem(element, options); - case "user": return InternalRealtimeRequestUserMessageItem.DeserializeInternalRealtimeRequestUserMessageItem(element, options); + case "message": + return InternalRealtimeRequestMessageItem.DeserializeInternalRealtimeRequestMessageItem(element, options); + case "function_call": + return InternalRealtimeRequestFunctionCallItem.DeserializeInternalRealtimeRequestFunctionCallItem(element, options); + case "function_call_output": + return InternalRealtimeRequestFunctionCallOutputItem.DeserializeInternalRealtimeRequestFunctionCallOutputItem(element, options); } } return UnknownRealtimeRequestItem.DeserializeUnknownRealtimeRequestItem(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +110,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ConversationItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItem(document.RootElement, options); } default: @@ -119,15 +129,20 @@ ConversationItem IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItem conversationItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItem(document.RootElement); + if (conversationItem == null) + { + return null; + } + return BinaryContent.Create(conversationItem, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItem.cs b/src/Generated/Models/ConversationItem.cs index 174f85a0d..90e10fc28 100644 --- a/src/Generated/Models/ConversationItem.cs +++ b/src/Generated/Models/ConversationItem.cs @@ -9,19 +9,28 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationItem { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationItem() + private protected IDictionary _additionalBinaryDataProperties; + + private protected ConversationItem(InternalRealtimeItemType @type) { + Type = @type; } - internal ConversationItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData) + internal ConversationItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Id = id; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal InternalRealtimeItemType Type { get; set; } + public string Id { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationItemCreatedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemCreatedUpdate.Serialization.cs index acf144430..57384093e 100644 --- a/src/Generated/Models/ConversationItemCreatedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemCreatedUpdate.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemCreatedUpdate : IJsonModel { + internal ConversationItemCreatedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemCreatedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("previous_item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("previous_item_id") != true) { writer.WritePropertyName("previous_item_id"u8); writer.WriteStringValue(PreviousItemId); } - if (SerializedAdditionalRawData?.ContainsKey("item") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item") != true) { writer.WritePropertyName("item"u8); writer.WriteObjectValue(_internalItem, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemCreatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemCreatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemCreatedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemCreatedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemCreatedUpdate(document.RootElement, options); } - internal static ConversationItemCreatedUpdate DeserializeConversationItemCreatedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemCreatedUpdate DeserializeConversationItemCreatedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string previousItemId = default; - InternalRealtimeResponseItem item = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string previousItemId = default; + InternalRealtimeResponseItem internalItem = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("previous_item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - previousItemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item"u8)) + if (prop.NameEquals("type"u8)) { - item = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(property.Value, options); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("previous_item_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + previousItemId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item"u8)) { - eventId = property.Value.GetString(); + internalItem = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationItemCreatedUpdate(type, eventId, serializedAdditionalRawData, previousItemId, item); + return new ConversationItemCreatedUpdate(eventId, kind, additionalBinaryDataProperties, previousItemId, internalItem); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - ConversationItemCreatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemCreatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemCreatedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemCreatedUpdate(document.RootElement, options); } default: @@ -152,15 +131,20 @@ ConversationItemCreatedUpdate IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemCreatedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemCreatedUpdate conversationItemCreatedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemCreatedUpdate(document.RootElement); + if (conversationItemCreatedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemCreatedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemCreatedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemCreatedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemCreatedUpdate.cs b/src/Generated/Models/ConversationItemCreatedUpdate.cs index 2d23c315c..ea9d33b3d 100644 --- a/src/Generated/Models/ConversationItemCreatedUpdate.cs +++ b/src/Generated/Models/ConversationItemCreatedUpdate.cs @@ -9,27 +9,18 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemCreatedUpdate : ConversationUpdate { - internal ConversationItemCreatedUpdate(string eventId, string previousItemId, InternalRealtimeResponseItem internalItem) : base(eventId) + internal ConversationItemCreatedUpdate(string eventId, string previousItemId, InternalRealtimeResponseItem internalItem) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemCreated) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(previousItemId, nameof(previousItemId)); - Argument.AssertNotNull(internalItem, nameof(internalItem)); - - Kind = ConversationUpdateKind.ItemCreated; PreviousItemId = previousItemId; _internalItem = internalItem; } - internal ConversationItemCreatedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string previousItemId, InternalRealtimeResponseItem internalItem) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemCreatedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string previousItemId, InternalRealtimeResponseItem internalItem) : base(eventId, kind, additionalBinaryDataProperties) { PreviousItemId = previousItemId; _internalItem = internalItem; } - internal ConversationItemCreatedUpdate() - { - } - public string PreviousItemId { get; } } } diff --git a/src/Generated/Models/ConversationItemDeletedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemDeletedUpdate.Serialization.cs index d4c875047..73928f1ee 100644 --- a/src/Generated/Models/ConversationItemDeletedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemDeletedUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemDeletedUpdate : IJsonModel { + internal ConversationItemDeletedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemDeletedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemDeletedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemDeletedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemDeletedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemDeletedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemDeletedUpdate(document.RootElement, options); } - internal static ConversationItemDeletedUpdate DeserializeConversationItemDeletedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemDeletedUpdate DeserializeConversationItemDeletedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string itemId = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string itemId = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - itemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item_id"u8)) { - eventId = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationItemDeletedUpdate(type, eventId, serializedAdditionalRawData, itemId); + return new ConversationItemDeletedUpdate(eventId, kind, additionalBinaryDataProperties, itemId); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - ConversationItemDeletedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemDeletedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemDeletedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemDeletedUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationItemDeletedUpdate IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemDeletedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemDeletedUpdate conversationItemDeletedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemDeletedUpdate(document.RootElement); + if (conversationItemDeletedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemDeletedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemDeletedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemDeletedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemDeletedUpdate.cs b/src/Generated/Models/ConversationItemDeletedUpdate.cs index 38fa3ac88..cf51f880f 100644 --- a/src/Generated/Models/ConversationItemDeletedUpdate.cs +++ b/src/Generated/Models/ConversationItemDeletedUpdate.cs @@ -9,24 +9,16 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemDeletedUpdate : ConversationUpdate { - internal ConversationItemDeletedUpdate(string eventId, string itemId) : base(eventId) + internal ConversationItemDeletedUpdate(string eventId, string itemId) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemDeleted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.ItemDeleted; ItemId = itemId; } - internal ConversationItemDeletedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string itemId) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemDeletedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId) : base(eventId, kind, additionalBinaryDataProperties) { ItemId = itemId; } - internal ConversationItemDeletedUpdate() - { - } - public string ItemId { get; } } } diff --git a/src/Generated/Models/ConversationItemStatus.cs b/src/Generated/Models/ConversationItemStatus.cs index c99155d0b..ea8827bd8 100644 --- a/src/Generated/Models/ConversationItemStatus.cs +++ b/src/Generated/Models/ConversationItemStatus.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationItemStatus : IEquatable { private readonly string _value; + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string IncompleteValue = "incomplete"; public ConversationItemStatus(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string InProgressValue = "in_progress"; - private const string CompletedValue = "completed"; - private const string IncompleteValue = "incomplete"; + _value = value; + } public static ConversationItemStatus InProgress { get; } = new ConversationItemStatus(InProgressValue); + public static ConversationItemStatus Completed { get; } = new ConversationItemStatus(CompletedValue); + public static ConversationItemStatus Incomplete { get; } = new ConversationItemStatus(IncompleteValue); + public static bool operator ==(ConversationItemStatus left, ConversationItemStatus right) => left.Equals(right); + public static bool operator !=(ConversationItemStatus left, ConversationItemStatus right) => !left.Equals(right); + public static implicit operator ConversationItemStatus(string value) => new ConversationItemStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationItemStatus other && Equals(other); + public bool Equals(ConversationItemStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.Serialization.cs index c21987a91..ac6ea7c7c 100644 --- a/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.Serialization.cs @@ -7,153 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingAudioFinishedUpdate : IJsonModel { + internal ConversationItemStreamingAudioFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemStreamingAudioFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemStreamingAudioFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemStreamingAudioFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemStreamingAudioFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemStreamingAudioFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemStreamingAudioFinishedUpdate(document.RootElement, options); } - internal static ConversationItemStreamingAudioFinishedUpdate DeserializeConversationItemStreamingAudioFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemStreamingAudioFinishedUpdate DeserializeConversationItemStreamingAudioFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("output_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("content_index"u8)) { - eventId = property.Value.GetString(); + contentIndex = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemStreamingAudioFinishedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, contentIndex); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -163,15 +141,16 @@ BinaryData IPersistableModel.Write } } - ConversationItemStreamingAudioFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemStreamingAudioFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemStreamingAudioFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemStreamingAudioFinishedUpdate(document.RootElement, options); } default: @@ -181,15 +160,20 @@ ConversationItemStreamingAudioFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemStreamingAudioFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemStreamingAudioFinishedUpdate conversationItemStreamingAudioFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemStreamingAudioFinishedUpdate(document.RootElement); + if (conversationItemStreamingAudioFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemStreamingAudioFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemStreamingAudioFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemStreamingAudioFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.cs b/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.cs index 58c85f623..95ff09046 100644 --- a/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.cs +++ b/src/Generated/Models/ConversationItemStreamingAudioFinishedUpdate.cs @@ -9,20 +9,15 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingAudioFinishedUpdate : ConversationUpdate { - internal ConversationItemStreamingAudioFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex) : base(eventId) + internal ConversationItemStreamingAudioFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.ItemStreamingPartAudioFinished; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; ContentIndex = contentIndex; } - internal ConversationItemStreamingAudioFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemStreamingAudioFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -30,13 +25,12 @@ internal ConversationItemStreamingAudioFinishedUpdate(ConversationUpdateKind kin ContentIndex = contentIndex; } - internal ConversationItemStreamingAudioFinishedUpdate() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } } } diff --git a/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.Serialization.cs index 15a4b862d..328a2fd15 100644 --- a/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingAudioTranscriptionFinishedUpdate : IJsonModel { + internal ConversationItemStreamingAudioTranscriptionFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemStreamingAudioTranscriptionFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("transcript") != true) + if (_additionalBinaryDataProperties?.ContainsKey("transcript") != true) { writer.WritePropertyName("transcript"u8); writer.WriteStringValue(Transcript); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemStreamingAudioTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemStreamingAudioTranscriptionFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemStreamingAudioTranscriptionFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemStreamingAudioTranscriptionFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(document.RootElement, options); } - internal static ConversationItemStreamingAudioTranscriptionFinishedUpdate DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemStreamingAudioTranscriptionFinishedUpdate DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; string transcript = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("transcript"u8)) + if (prop.NameEquals("output_index"u8)) { - transcript = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("transcript"u8)) { - eventId = property.Value.GetString(); + transcript = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemStreamingAudioTranscriptionFinishedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static ConversationItemStreamingAudioTranscriptionFinishedUpdate Deseri transcript); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemStreamingAudioTranscriptionFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemStreamingAudioTranscriptionFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(document.RootElement, options); } default: @@ -193,15 +172,20 @@ ConversationItemStreamingAudioTranscriptionFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemStreamingAudioTranscriptionFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemStreamingAudioTranscriptionFinishedUpdate conversationItemStreamingAudioTranscriptionFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(document.RootElement); + if (conversationItemStreamingAudioTranscriptionFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemStreamingAudioTranscriptionFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemStreamingAudioTranscriptionFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemStreamingAudioTranscriptionFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.cs b/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.cs index af1a3426a..32c919a71 100644 --- a/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.cs +++ b/src/Generated/Models/ConversationItemStreamingAudioTranscriptionFinishedUpdate.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingAudioTranscriptionFinishedUpdate : ConversationUpdate { - internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string transcript) : base(eventId) + internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string transcript) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioTranscriptionFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(transcript, nameof(transcript)); - - Kind = ConversationUpdateKind.ItemStreamingPartAudioTranscriptionFinished; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventI Transcript = transcript; } - internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, string transcript) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, string transcript) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,14 +27,14 @@ internal ConversationItemStreamingAudioTranscriptionFinishedUpdate(ConversationU Transcript = transcript; } - internal ConversationItemStreamingAudioTranscriptionFinishedUpdate() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } + public string Transcript { get; } } } diff --git a/src/Generated/Models/ConversationItemStreamingFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemStreamingFinishedUpdate.Serialization.cs index f4b89847a..2fc545199 100644 --- a/src/Generated/Models/ConversationItemStreamingFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemStreamingFinishedUpdate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingFinishedUpdate : IJsonModel { + internal ConversationItemStreamingFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemStreamingFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("item") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item") != true) { writer.WritePropertyName("item"u8); writer.WriteObjectValue(_internalItem, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemStreamingFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemStreamingFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemStreamingFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemStreamingFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemStreamingFinishedUpdate(document.RootElement, options); } - internal static ConversationItemStreamingFinishedUpdate DeserializeConversationItemStreamingFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemStreamingFinishedUpdate DeserializeConversationItemStreamingFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; int outputIndex = default; - InternalRealtimeResponseItem item = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalRealtimeResponseItem internalItem = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("type"u8)) { - outputIndex = property.Value.GetInt32(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("item"u8)) + if (prop.NameEquals("response_id"u8)) { - item = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(property.Value, options); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("output_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item"u8)) { - eventId = property.Value.GetString(); + internalItem = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemStreamingFinishedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, outputIndex, - item); + internalItem); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Write(Mode } } - ConversationItemStreamingFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemStreamingFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemStreamingFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemStreamingFinishedUpdate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ ConversationItemStreamingFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemStreamingFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemStreamingFinishedUpdate conversationItemStreamingFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemStreamingFinishedUpdate(document.RootElement); + if (conversationItemStreamingFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemStreamingFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemStreamingFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemStreamingFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemStreamingFinishedUpdate.cs b/src/Generated/Models/ConversationItemStreamingFinishedUpdate.cs index 8fca906d4..a178fe402 100644 --- a/src/Generated/Models/ConversationItemStreamingFinishedUpdate.cs +++ b/src/Generated/Models/ConversationItemStreamingFinishedUpdate.cs @@ -9,30 +9,22 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingFinishedUpdate : ConversationUpdate { - internal ConversationItemStreamingFinishedUpdate(string eventId, string responseId, int outputIndex, InternalRealtimeResponseItem internalItem) : base(eventId) + internal ConversationItemStreamingFinishedUpdate(string eventId, string responseId, int outputIndex, InternalRealtimeResponseItem internalItem) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(internalItem, nameof(internalItem)); - - Kind = ConversationUpdateKind.ItemStreamingFinished; ResponseId = responseId; OutputIndex = outputIndex; _internalItem = internalItem; } - internal ConversationItemStreamingFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, int outputIndex, InternalRealtimeResponseItem internalItem) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemStreamingFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, int outputIndex, InternalRealtimeResponseItem internalItem) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; OutputIndex = outputIndex; _internalItem = internalItem; } - internal ConversationItemStreamingFinishedUpdate() - { - } - public string ResponseId { get; } + public int OutputIndex { get; } } } diff --git a/src/Generated/Models/ConversationItemStreamingStartedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemStreamingStartedUpdate.Serialization.cs index f4c01eaca..e0e227030 100644 --- a/src/Generated/Models/ConversationItemStreamingStartedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemStreamingStartedUpdate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingStartedUpdate : IJsonModel { + internal ConversationItemStreamingStartedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemStreamingStartedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(ItemIndex); } - if (SerializedAdditionalRawData?.ContainsKey("item") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item") != true) { writer.WritePropertyName("item"u8); writer.WriteObjectValue(_internalItem, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemStreamingStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemStreamingStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemStreamingStartedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemStreamingStartedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemStreamingStartedUpdate(document.RootElement, options); } - internal static ConversationItemStreamingStartedUpdate DeserializeConversationItemStreamingStartedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemStreamingStartedUpdate DeserializeConversationItemStreamingStartedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string responseId = default; - int outputIndex = default; - InternalRealtimeResponseItem item = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string responseId = default; + int itemIndex = default; + InternalRealtimeResponseItem internalItem = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("type"u8)) { - outputIndex = property.Value.GetInt32(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("item"u8)) + if (prop.NameEquals("response_id"u8)) { - item = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(property.Value, options); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("output_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + itemIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item"u8)) { - eventId = property.Value.GetString(); + internalItem = InternalRealtimeResponseItem.DeserializeInternalRealtimeResponseItem(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemStreamingStartedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, - outputIndex, - item); + itemIndex, + internalItem); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Write(Model } } - ConversationItemStreamingStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemStreamingStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemStreamingStartedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemStreamingStartedUpdate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ ConversationItemStreamingStartedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemStreamingStartedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemStreamingStartedUpdate conversationItemStreamingStartedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemStreamingStartedUpdate(document.RootElement); + if (conversationItemStreamingStartedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemStreamingStartedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemStreamingStartedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemStreamingStartedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemStreamingStartedUpdate.cs b/src/Generated/Models/ConversationItemStreamingStartedUpdate.cs index 10d04b0f3..227fad3fd 100644 --- a/src/Generated/Models/ConversationItemStreamingStartedUpdate.cs +++ b/src/Generated/Models/ConversationItemStreamingStartedUpdate.cs @@ -9,29 +9,20 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingStartedUpdate : ConversationUpdate { - internal ConversationItemStreamingStartedUpdate(string eventId, string responseId, int itemIndex, InternalRealtimeResponseItem internalItem) : base(eventId) + internal ConversationItemStreamingStartedUpdate(string eventId, string responseId, int itemIndex, InternalRealtimeResponseItem internalItem) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingStarted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(internalItem, nameof(internalItem)); - - Kind = ConversationUpdateKind.ItemStreamingStarted; ResponseId = responseId; ItemIndex = itemIndex; _internalItem = internalItem; } - internal ConversationItemStreamingStartedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, int itemIndex, InternalRealtimeResponseItem internalItem) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemStreamingStartedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, int itemIndex, InternalRealtimeResponseItem internalItem) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemIndex = itemIndex; _internalItem = internalItem; } - internal ConversationItemStreamingStartedUpdate() - { - } - public string ResponseId { get; } } } diff --git a/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.Serialization.cs index 952a88022..7fcbc0dbc 100644 --- a/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingTextFinishedUpdate : IJsonModel { + internal ConversationItemStreamingTextFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemStreamingTextFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemStreamingTextFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemStreamingTextFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemStreamingTextFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemStreamingTextFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemStreamingTextFinishedUpdate(document.RootElement, options); } - internal static ConversationItemStreamingTextFinishedUpdate DeserializeConversationItemStreamingTextFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemStreamingTextFinishedUpdate DeserializeConversationItemStreamingTextFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; string text = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("output_index"u8)) { - text = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("text"u8)) { - eventId = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemStreamingTextFinishedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static ConversationItemStreamingTextFinishedUpdate DeserializeConversat text); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Write( } } - ConversationItemStreamingTextFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemStreamingTextFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemStreamingTextFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemStreamingTextFinishedUpdate(document.RootElement, options); } default: @@ -193,15 +172,20 @@ ConversationItemStreamingTextFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemStreamingTextFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemStreamingTextFinishedUpdate conversationItemStreamingTextFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemStreamingTextFinishedUpdate(document.RootElement); + if (conversationItemStreamingTextFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemStreamingTextFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemStreamingTextFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemStreamingTextFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.cs b/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.cs index 470d45211..4fa53a154 100644 --- a/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.cs +++ b/src/Generated/Models/ConversationItemStreamingTextFinishedUpdate.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemStreamingTextFinishedUpdate : ConversationUpdate { - internal ConversationItemStreamingTextFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string text) : base(eventId) + internal ConversationItemStreamingTextFinishedUpdate(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string text) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartTextFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(text, nameof(text)); - - Kind = ConversationUpdateKind.ItemStreamingPartTextFinished; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal ConversationItemStreamingTextFinishedUpdate(string eventId, string resp Text = text; } - internal ConversationItemStreamingTextFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, string text) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemStreamingTextFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, string text) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,14 +27,14 @@ internal ConversationItemStreamingTextFinishedUpdate(ConversationUpdateKind kind Text = text; } - internal ConversationItemStreamingTextFinishedUpdate() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } + public string Text { get; } } } diff --git a/src/Generated/Models/ConversationItemTruncatedUpdate.Serialization.cs b/src/Generated/Models/ConversationItemTruncatedUpdate.Serialization.cs index 5a2a2824d..8560e0f66 100644 --- a/src/Generated/Models/ConversationItemTruncatedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationItemTruncatedUpdate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationItemTruncatedUpdate : IJsonModel { + internal ConversationItemTruncatedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItemTruncatedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("audio_end_ms") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_end_ms") != true) { writer.WritePropertyName("audio_end_ms"u8); writer.WriteNumberValue(AudioEndMs); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationItemTruncatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItemTruncatedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationItemTruncatedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItemTruncatedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItemTruncatedUpdate(document.RootElement, options); } - internal static ConversationItemTruncatedUpdate DeserializeConversationItemTruncatedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationItemTruncatedUpdate DeserializeConversationItemTruncatedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string itemId = default; int contentIndex = default; int audioEndMs = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("event_id"u8)) { - itemId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("type"u8)) { - contentIndex = property.Value.GetInt32(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("audio_end_ms"u8)) + if (prop.NameEquals("item_id"u8)) { - audioEndMs = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("audio_end_ms"u8)) { - eventId = property.Value.GetString(); + audioEndMs = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationItemTruncatedUpdate( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, itemId, contentIndex, audioEndMs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - ConversationItemTruncatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItemTruncatedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationItemTruncatedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItemTruncatedUpdate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ ConversationItemTruncatedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationItemTruncatedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationItemTruncatedUpdate conversationItemTruncatedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationItemTruncatedUpdate(document.RootElement); + if (conversationItemTruncatedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationItemTruncatedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationItemTruncatedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationItemTruncatedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationItemTruncatedUpdate.cs b/src/Generated/Models/ConversationItemTruncatedUpdate.cs index 66aba0d4c..af0f9a51a 100644 --- a/src/Generated/Models/ConversationItemTruncatedUpdate.cs +++ b/src/Generated/Models/ConversationItemTruncatedUpdate.cs @@ -9,30 +9,24 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationItemTruncatedUpdate : ConversationUpdate { - internal ConversationItemTruncatedUpdate(string eventId, string itemId, int contentIndex, int audioEndMs) : base(eventId) + internal ConversationItemTruncatedUpdate(string eventId, string itemId, int contentIndex, int audioEndMs) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemTruncated) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - - Kind = ConversationUpdateKind.ItemTruncated; ItemId = itemId; ContentIndex = contentIndex; AudioEndMs = audioEndMs; } - internal ConversationItemTruncatedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string itemId, int contentIndex, int audioEndMs) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationItemTruncatedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string itemId, int contentIndex, int audioEndMs) : base(eventId, kind, additionalBinaryDataProperties) { ItemId = itemId; ContentIndex = contentIndex; AudioEndMs = audioEndMs; } - internal ConversationItemTruncatedUpdate() - { - } - public string ItemId { get; } + public int ContentIndex { get; } + public int AudioEndMs { get; } } } diff --git a/src/Generated/Models/ConversationMessageRole.cs b/src/Generated/Models/ConversationMessageRole.cs index b5cd90fd4..cf5d494e2 100644 --- a/src/Generated/Models/ConversationMessageRole.cs +++ b/src/Generated/Models/ConversationMessageRole.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationMessageRole : IEquatable { private readonly string _value; + private const string SystemValue = "system"; + private const string UserValue = "user"; + private const string AssistantValue = "assistant"; public ConversationMessageRole(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string SystemValue = "system"; - private const string UserValue = "user"; - private const string AssistantValue = "assistant"; + _value = value; + } public static ConversationMessageRole System { get; } = new ConversationMessageRole(SystemValue); + public static ConversationMessageRole User { get; } = new ConversationMessageRole(UserValue); + public static ConversationMessageRole Assistant { get; } = new ConversationMessageRole(AssistantValue); + public static bool operator ==(ConversationMessageRole left, ConversationMessageRole right) => left.Equals(right); + public static bool operator !=(ConversationMessageRole left, ConversationMessageRole right) => !left.Equals(right); + public static implicit operator ConversationMessageRole(string value) => new ConversationMessageRole(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationMessageRole other && Equals(other); + public bool Equals(ConversationMessageRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationOutputTokenUsageDetails.Serialization.cs b/src/Generated/Models/ConversationOutputTokenUsageDetails.Serialization.cs index 7aa592b03..35403bdb8 100644 --- a/src/Generated/Models/ConversationOutputTokenUsageDetails.Serialization.cs +++ b/src/Generated/Models/ConversationOutputTokenUsageDetails.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationOutputTokenUsageDetails : IJsonModel { + internal ConversationOutputTokenUsageDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationOutputTokenUsageDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text_tokens") != true) { writer.WritePropertyName("text_tokens"u8); writer.WriteNumberValue(TextTokens); } - if (SerializedAdditionalRawData?.ContainsKey("audio_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_tokens") != true) { writer.WritePropertyName("audio_tokens"u8); writer.WriteNumberValue(AudioTokens); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer #endif } } - writer.WriteEndObject(); } - ConversationOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationOutputTokenUsageDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationOutputTokenUsageDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationOutputTokenUsageDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationOutputTokenUsageDetails(document.RootElement, options); } - internal static ConversationOutputTokenUsageDetails DeserializeConversationOutputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationOutputTokenUsageDetails DeserializeConversationOutputTokenUsageDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } int textTokens = default; int audioTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text_tokens"u8)) + if (prop.NameEquals("text_tokens"u8)) { - textTokens = property.Value.GetInt32(); + textTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("audio_tokens"u8)) + if (prop.NameEquals("audio_tokens"u8)) { - audioTokens = property.Value.GetInt32(); + audioTokens = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationOutputTokenUsageDetails(textTokens, audioTokens, serializedAdditionalRawData); + return new ConversationOutputTokenUsageDetails(textTokens, audioTokens, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - ConversationOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationOutputTokenUsageDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationOutputTokenUsageDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationOutputTokenUsageDetails(document.RootElement, options); } default: @@ -130,15 +137,20 @@ ConversationOutputTokenUsageDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationOutputTokenUsageDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationOutputTokenUsageDetails conversationOutputTokenUsageDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationOutputTokenUsageDetails(document.RootElement); + if (conversationOutputTokenUsageDetails == null) + { + return null; + } + return BinaryContent.Create(conversationOutputTokenUsageDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationOutputTokenUsageDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationOutputTokenUsageDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationOutputTokenUsageDetails.cs b/src/Generated/Models/ConversationOutputTokenUsageDetails.cs index e6c4b4172..0a424eadc 100644 --- a/src/Generated/Models/ConversationOutputTokenUsageDetails.cs +++ b/src/Generated/Models/ConversationOutputTokenUsageDetails.cs @@ -9,25 +9,29 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationOutputTokenUsageDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ConversationOutputTokenUsageDetails(int textTokens, int audioTokens) { TextTokens = textTokens; AudioTokens = audioTokens; } - internal ConversationOutputTokenUsageDetails(int textTokens, int audioTokens, IDictionary serializedAdditionalRawData) + internal ConversationOutputTokenUsageDetails(int textTokens, int audioTokens, IDictionary additionalBinaryDataProperties) { TextTokens = textTokens; AudioTokens = audioTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ConversationOutputTokenUsageDetails() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int TextTokens { get; } + public int AudioTokens { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationRateLimitDetailsItem.Serialization.cs b/src/Generated/Models/ConversationRateLimitDetailsItem.Serialization.cs index b149c1433..1579cc3cf 100644 --- a/src/Generated/Models/ConversationRateLimitDetailsItem.Serialization.cs +++ b/src/Generated/Models/ConversationRateLimitDetailsItem.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationRateLimitDetailsItem : IJsonModel { + internal ConversationRateLimitDetailsItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationRateLimitDetailsItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("limit") != true) + if (_additionalBinaryDataProperties?.ContainsKey("limit") != true) { writer.WritePropertyName("limit"u8); writer.WriteNumberValue(MaximumCount); } - if (SerializedAdditionalRawData?.ContainsKey("remaining") != true) + if (_additionalBinaryDataProperties?.ContainsKey("remaining") != true) { writer.WritePropertyName("remaining"u8); writer.WriteNumberValue(RemainingCount); } - if (SerializedAdditionalRawData?.ContainsKey("reset_seconds") != true) + if (_additionalBinaryDataProperties?.ContainsKey("reset_seconds") != true) { writer.WritePropertyName("reset_seconds"u8); writer.WriteNumberValue(Convert.ToDouble(TimeUntilReset.ToString("s\\.FFF"))); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,71 +70,67 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - ConversationRateLimitDetailsItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationRateLimitDetailsItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationRateLimitDetailsItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationRateLimitDetailsItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationRateLimitDetailsItem(document.RootElement, options); } - internal static ConversationRateLimitDetailsItem DeserializeConversationRateLimitDetailsItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationRateLimitDetailsItem DeserializeConversationRateLimitDetailsItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - int limit = default; - int remaining = default; - TimeSpan resetSeconds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int maximumCount = default; + int remainingCount = default; + TimeSpan timeUntilReset = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("limit"u8)) + if (prop.NameEquals("limit"u8)) { - limit = property.Value.GetInt32(); + maximumCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("remaining"u8)) + if (prop.NameEquals("remaining"u8)) { - remaining = property.Value.GetInt32(); + remainingCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("reset_seconds"u8)) + if (prop.NameEquals("reset_seconds"u8)) { - resetSeconds = TimeSpan.FromSeconds(property.Value.GetDouble()); + timeUntilReset = TimeSpan.FromSeconds(prop.Value.GetDouble()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationRateLimitDetailsItem(name, limit, remaining, resetSeconds, serializedAdditionalRawData); + return new ConversationRateLimitDetailsItem(name, maximumCount, remainingCount, timeUntilReset, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - ConversationRateLimitDetailsItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationRateLimitDetailsItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationRateLimitDetailsItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationRateLimitDetailsItem(document.RootElement, options); } default: @@ -152,15 +159,20 @@ ConversationRateLimitDetailsItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationRateLimitDetailsItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationRateLimitDetailsItem conversationRateLimitDetailsItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationRateLimitDetailsItem(document.RootElement); + if (conversationRateLimitDetailsItem == null) + { + return null; + } + return BinaryContent.Create(conversationRateLimitDetailsItem, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationRateLimitDetailsItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationRateLimitDetailsItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationRateLimitDetailsItem.cs b/src/Generated/Models/ConversationRateLimitDetailsItem.cs index 39b176e7c..e0986111a 100644 --- a/src/Generated/Models/ConversationRateLimitDetailsItem.cs +++ b/src/Generated/Models/ConversationRateLimitDetailsItem.cs @@ -9,30 +9,31 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationRateLimitDetailsItem { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ConversationRateLimitDetailsItem(string name, int maximumCount, int remainingCount, TimeSpan timeUntilReset) { - Argument.AssertNotNull(name, nameof(name)); - Name = name; MaximumCount = maximumCount; RemainingCount = remainingCount; TimeUntilReset = timeUntilReset; } - internal ConversationRateLimitDetailsItem(string name, int maximumCount, int remainingCount, TimeSpan timeUntilReset, IDictionary serializedAdditionalRawData) + internal ConversationRateLimitDetailsItem(string name, int maximumCount, int remainingCount, TimeSpan timeUntilReset, IDictionary additionalBinaryDataProperties) { Name = name; MaximumCount = maximumCount; RemainingCount = remainingCount; TimeUntilReset = timeUntilReset; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ConversationRateLimitDetailsItem() + public string Name { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; } } } diff --git a/src/Generated/Models/ConversationRateLimitsUpdate.Serialization.cs b/src/Generated/Models/ConversationRateLimitsUpdate.Serialization.cs index 57205074b..b5f2a7e07 100644 --- a/src/Generated/Models/ConversationRateLimitsUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationRateLimitsUpdate.Serialization.cs @@ -7,123 +7,101 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationRateLimitsUpdate : IJsonModel { + internal ConversationRateLimitsUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationRateLimitsUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("rate_limits") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("rate_limits") != true) { writer.WritePropertyName("rate_limits"u8); writer.WriteStartArray(); - foreach (var item in AllDetails) + foreach (ConversationRateLimitDetailsItem item in AllDetails) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationRateLimitsUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationRateLimitsUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationRateLimitsUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationRateLimitsUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationRateLimitsUpdate(document.RootElement, options); } - internal static ConversationRateLimitsUpdate DeserializeConversationRateLimitsUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationRateLimitsUpdate DeserializeConversationRateLimitsUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList rateLimits = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + IReadOnlyList allDetails = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("rate_limits"u8)) + if (prop.NameEquals("event_id"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationRateLimitDetailsItem.DeserializeConversationRateLimitDetailsItem(item, options)); - } - rateLimits = array; + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("rate_limits"u8)) { - eventId = property.Value.GetString(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationRateLimitDetailsItem.DeserializeConversationRateLimitDetailsItem(item, options)); + } + allDetails = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationRateLimitsUpdate(type, eventId, serializedAdditionalRawData, rateLimits); + return new ConversationRateLimitsUpdate(eventId, kind, additionalBinaryDataProperties, allDetails); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -133,15 +111,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - ConversationRateLimitsUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationRateLimitsUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationRateLimitsUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationRateLimitsUpdate(document.RootElement, options); } default: @@ -151,15 +130,20 @@ ConversationRateLimitsUpdate IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationRateLimitsUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationRateLimitsUpdate conversationRateLimitsUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationRateLimitsUpdate(document.RootElement); + if (conversationRateLimitsUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationRateLimitsUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationRateLimitsUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationRateLimitsUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationRateLimitsUpdate.cs b/src/Generated/Models/ConversationRateLimitsUpdate.cs index c83155a91..446f87f45 100644 --- a/src/Generated/Models/ConversationRateLimitsUpdate.cs +++ b/src/Generated/Models/ConversationRateLimitsUpdate.cs @@ -10,22 +10,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationRateLimitsUpdate : ConversationUpdate { - internal ConversationRateLimitsUpdate(string eventId, IEnumerable allDetails) : base(eventId) + internal ConversationRateLimitsUpdate(string eventId, IEnumerable allDetails) : base(eventId, RealtimeConversation.ConversationUpdateKind.RateLimitsUpdated) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(allDetails, nameof(allDetails)); - - Kind = ConversationUpdateKind.RateLimitsUpdated; AllDetails = allDetails.ToList(); } - internal ConversationRateLimitsUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, IReadOnlyList allDetails) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationRateLimitsUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, IReadOnlyList allDetails) : base(eventId, kind, additionalBinaryDataProperties) { AllDetails = allDetails; } - - internal ConversationRateLimitsUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationResponseFinishedUpdate.Serialization.cs b/src/Generated/Models/ConversationResponseFinishedUpdate.Serialization.cs index dc967ad8b..4f77c879b 100644 --- a/src/Generated/Models/ConversationResponseFinishedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationResponseFinishedUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationResponseFinishedUpdate : IJsonModel { + internal ConversationResponseFinishedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationResponseFinishedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response") != true) { writer.WritePropertyName("response"u8); writer.WriteObjectValue(_internalResponse, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationResponseFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationResponseFinishedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationResponseFinishedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationResponseFinishedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationResponseFinishedUpdate(document.RootElement, options); } - internal static ConversationResponseFinishedUpdate DeserializeConversationResponseFinishedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationResponseFinishedUpdate DeserializeConversationResponseFinishedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeResponse response = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeResponse internalResponse = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response"u8)) + if (prop.NameEquals("event_id"u8)) { - response = InternalRealtimeResponse.DeserializeInternalRealtimeResponse(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("response"u8)) { - eventId = property.Value.GetString(); + internalResponse = InternalRealtimeResponse.DeserializeInternalRealtimeResponse(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationResponseFinishedUpdate(type, eventId, serializedAdditionalRawData, response); + return new ConversationResponseFinishedUpdate(eventId, kind, additionalBinaryDataProperties, internalResponse); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - ConversationResponseFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationResponseFinishedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationResponseFinishedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationResponseFinishedUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationResponseFinishedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationResponseFinishedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationResponseFinishedUpdate conversationResponseFinishedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationResponseFinishedUpdate(document.RootElement); + if (conversationResponseFinishedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationResponseFinishedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationResponseFinishedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationResponseFinishedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationResponseFinishedUpdate.cs b/src/Generated/Models/ConversationResponseFinishedUpdate.cs index ca6151598..9f8a13be7 100644 --- a/src/Generated/Models/ConversationResponseFinishedUpdate.cs +++ b/src/Generated/Models/ConversationResponseFinishedUpdate.cs @@ -9,22 +9,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationResponseFinishedUpdate : ConversationUpdate { - internal ConversationResponseFinishedUpdate(string eventId, InternalRealtimeResponse internalResponse) : base(eventId) + internal ConversationResponseFinishedUpdate(string eventId, InternalRealtimeResponse internalResponse) : base(eventId, RealtimeConversation.ConversationUpdateKind.ResponseFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(internalResponse, nameof(internalResponse)); - - Kind = ConversationUpdateKind.ResponseFinished; _internalResponse = internalResponse; } - internal ConversationResponseFinishedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeResponse internalResponse) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationResponseFinishedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeResponse internalResponse) : base(eventId, kind, additionalBinaryDataProperties) { _internalResponse = internalResponse; } - - internal ConversationResponseFinishedUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationResponseStartedUpdate.Serialization.cs b/src/Generated/Models/ConversationResponseStartedUpdate.Serialization.cs index 45e665ca7..c449ef621 100644 --- a/src/Generated/Models/ConversationResponseStartedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationResponseStartedUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationResponseStartedUpdate : IJsonModel { + internal ConversationResponseStartedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationResponseStartedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response") != true) { writer.WritePropertyName("response"u8); writer.WriteObjectValue(_internalResponse, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationResponseStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationResponseStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationResponseStartedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationResponseStartedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationResponseStartedUpdate(document.RootElement, options); } - internal static ConversationResponseStartedUpdate DeserializeConversationResponseStartedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationResponseStartedUpdate DeserializeConversationResponseStartedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeResponse response = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeResponse internalResponse = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response"u8)) + if (prop.NameEquals("event_id"u8)) { - response = InternalRealtimeResponse.DeserializeInternalRealtimeResponse(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("response"u8)) { - eventId = property.Value.GetString(); + internalResponse = InternalRealtimeResponse.DeserializeInternalRealtimeResponse(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationResponseStartedUpdate(type, eventId, serializedAdditionalRawData, response); + return new ConversationResponseStartedUpdate(eventId, kind, additionalBinaryDataProperties, internalResponse); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - ConversationResponseStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationResponseStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationResponseStartedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationResponseStartedUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationResponseStartedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationResponseStartedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationResponseStartedUpdate conversationResponseStartedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationResponseStartedUpdate(document.RootElement); + if (conversationResponseStartedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationResponseStartedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationResponseStartedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationResponseStartedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationResponseStartedUpdate.cs b/src/Generated/Models/ConversationResponseStartedUpdate.cs index 76bda8353..38759ffc4 100644 --- a/src/Generated/Models/ConversationResponseStartedUpdate.cs +++ b/src/Generated/Models/ConversationResponseStartedUpdate.cs @@ -9,22 +9,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationResponseStartedUpdate : ConversationUpdate { - internal ConversationResponseStartedUpdate(string eventId, InternalRealtimeResponse internalResponse) : base(eventId) + internal ConversationResponseStartedUpdate(string eventId, InternalRealtimeResponse internalResponse) : base(eventId, RealtimeConversation.ConversationUpdateKind.ResponseStarted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(internalResponse, nameof(internalResponse)); - - Kind = ConversationUpdateKind.ResponseStarted; _internalResponse = internalResponse; } - internal ConversationResponseStartedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeResponse internalResponse) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationResponseStartedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeResponse internalResponse) : base(eventId, kind, additionalBinaryDataProperties) { _internalResponse = internalResponse; } - - internal ConversationResponseStartedUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationSessionConfiguredUpdate.Serialization.cs b/src/Generated/Models/ConversationSessionConfiguredUpdate.Serialization.cs index 0db393533..ee62e9ca5 100644 --- a/src/Generated/Models/ConversationSessionConfiguredUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationSessionConfiguredUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationSessionConfiguredUpdate : IJsonModel { + internal ConversationSessionConfiguredUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationSessionConfiguredUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("session") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("session") != true) { writer.WritePropertyName("session"u8); writer.WriteObjectValue(_internalSession, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationSessionConfiguredUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationSessionConfiguredUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationSessionConfiguredUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationSessionConfiguredUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationSessionConfiguredUpdate(document.RootElement, options); } - internal static ConversationSessionConfiguredUpdate DeserializeConversationSessionConfiguredUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationSessionConfiguredUpdate DeserializeConversationSessionConfiguredUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeResponseSession session = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeResponseSession internalSession = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("session"u8)) + if (prop.NameEquals("event_id"u8)) { - session = InternalRealtimeResponseSession.DeserializeInternalRealtimeResponseSession(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("session"u8)) { - eventId = property.Value.GetString(); + internalSession = InternalRealtimeResponseSession.DeserializeInternalRealtimeResponseSession(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationSessionConfiguredUpdate(type, eventId, serializedAdditionalRawData, session); + return new ConversationSessionConfiguredUpdate(eventId, kind, additionalBinaryDataProperties, internalSession); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - ConversationSessionConfiguredUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationSessionConfiguredUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationSessionConfiguredUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationSessionConfiguredUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationSessionConfiguredUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationSessionConfiguredUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationSessionConfiguredUpdate conversationSessionConfiguredUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationSessionConfiguredUpdate(document.RootElement); + if (conversationSessionConfiguredUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationSessionConfiguredUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationSessionConfiguredUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationSessionConfiguredUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationSessionConfiguredUpdate.cs b/src/Generated/Models/ConversationSessionConfiguredUpdate.cs index 79fc02c99..65a084a4b 100644 --- a/src/Generated/Models/ConversationSessionConfiguredUpdate.cs +++ b/src/Generated/Models/ConversationSessionConfiguredUpdate.cs @@ -9,22 +9,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationSessionConfiguredUpdate : ConversationUpdate { - internal ConversationSessionConfiguredUpdate(string eventId, InternalRealtimeResponseSession internalSession) : base(eventId) + internal ConversationSessionConfiguredUpdate(string eventId, InternalRealtimeResponseSession internalSession) : base(eventId, RealtimeConversation.ConversationUpdateKind.SessionConfigured) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(internalSession, nameof(internalSession)); - - Kind = ConversationUpdateKind.SessionConfigured; _internalSession = internalSession; } - internal ConversationSessionConfiguredUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeResponseSession internalSession) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationSessionConfiguredUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeResponseSession internalSession) : base(eventId, kind, additionalBinaryDataProperties) { _internalSession = internalSession; } - - internal ConversationSessionConfiguredUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationSessionOptions.Serialization.cs b/src/Generated/Models/ConversationSessionOptions.Serialization.cs index 318f04af3..4a25c88a8 100644 --- a/src/Generated/Models/ConversationSessionOptions.Serialization.cs +++ b/src/Generated/Models/ConversationSessionOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,56 +15,54 @@ public partial class ConversationSessionOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationSessionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("modalities") != true && Optional.IsCollectionDefined(_internalModalities)) - { - writer.WritePropertyName("modalities"u8); - writer.WriteStartArray(); - foreach (var item in _internalModalities) - { - writer.WriteStringValue(item.ToString()); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(Instructions)) + if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { writer.WritePropertyName("instructions"u8); writer.WriteStringValue(Instructions); } - if (SerializedAdditionalRawData?.ContainsKey("voice") != true && Optional.IsDefined(Voice)) + if (Optional.IsDefined(Voice) && _additionalBinaryDataProperties?.ContainsKey("voice") != true) { writer.WritePropertyName("voice"u8); writer.WriteStringValue(Voice.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("input_audio_format") != true && Optional.IsDefined(InputAudioFormat)) + if (Optional.IsDefined(InputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("input_audio_format") != true) { writer.WritePropertyName("input_audio_format"u8); writer.WriteStringValue(InputAudioFormat.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("output_audio_format") != true && Optional.IsDefined(OutputAudioFormat)) + if (Optional.IsDefined(OutputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("output_audio_format") != true) { writer.WritePropertyName("output_audio_format"u8); writer.WriteStringValue(OutputAudioFormat.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("input_audio_transcription") != true && Optional.IsDefined(InputTranscriptionOptions)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { - if (InputTranscriptionOptions != null) - { - writer.WritePropertyName("input_audio_transcription"u8); - writer.WriteObjectValue(InputTranscriptionOptions, options); - } - else + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (ConversationTool item in Tools) { - writer.WriteNull("input_audio_transcription"); + writer.WriteObjectValue(item, options); } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); } - if (SerializedAdditionalRawData?.ContainsKey("turn_detection") != true && Optional.IsDefined(TurnDetectionOptions)) + if (Optional.IsDefined(TurnDetectionOptions) && _additionalBinaryDataProperties?.ContainsKey("turn_detection") != true) { if (TurnDetectionOptions != null) { @@ -72,24 +71,36 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } else { - writer.WriteNull("turn_detection"); + writer.WriteNull("turnDetection"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsDefined(InputTranscriptionOptions) && _additionalBinaryDataProperties?.ContainsKey("input_audio_transcription") != true) { - writer.WritePropertyName("tools"u8); + if (InputTranscriptionOptions != null) + { + writer.WritePropertyName("input_audio_transcription"u8); + writer.WriteObjectValue(InputTranscriptionOptions, options); + } + else + { + writer.WriteNull("inputAudioTranscription"u8); + } + } + if (Optional.IsCollectionDefined(_internalModalities) && _additionalBinaryDataProperties?.ContainsKey("modalities") != true) + { + writer.WritePropertyName("modalities"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (InternalRealtimeRequestSessionModality item in _internalModalities) { - writer.WriteObjectValue(item, options); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true && Optional.IsDefined(_internalToolChoice)) + if (Optional.IsDefined(_internalToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { writer.WritePropertyName("tool_choice"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(_internalToolChoice); + writer.WriteRawValue(_internalToolChoice); #else using (JsonDocument document = JsonDocument.Parse(_internalToolChoice)) { @@ -97,16 +108,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } #endif } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) - { - writer.WritePropertyName("temperature"u8); - writer.WriteNumberValue(Temperature.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("max_response_output_tokens") != true && Optional.IsDefined(_maxResponseOutputTokens)) + if (Optional.IsDefined(_maxResponseOutputTokens) && _additionalBinaryDataProperties?.ContainsKey("max_response_output_tokens") != true) { writer.WritePropertyName("max_response_output_tokens"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(_maxResponseOutputTokens); + writer.WriteRawValue(_maxResponseOutputTokens); #else using (JsonDocument document = JsonDocument.Parse(_maxResponseOutputTokens)) { @@ -114,9 +120,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -124,7 +130,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -133,177 +139,173 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - ConversationSessionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationSessionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationSessionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationSessionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationSessionOptions(document.RootElement, options); } - internal static ConversationSessionOptions DeserializeConversationSessionOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationSessionOptions DeserializeConversationSessionOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList modalities = default; string instructions = default; ConversationVoice? voice = default; ConversationAudioFormat? inputAudioFormat = default; ConversationAudioFormat? outputAudioFormat = default; - ConversationInputTranscriptionOptions inputAudioTranscription = default; - ConversationTurnDetectionOptions turnDetection = default; IList tools = default; - BinaryData toolChoice = default; float? temperature = default; + ConversationTurnDetectionOptions turnDetectionOptions = default; + ConversationInputTranscriptionOptions inputTranscriptionOptions = default; + IList internalModalities = default; + BinaryData internalToolChoice = default; BinaryData maxResponseOutputTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("modalities"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(new InternalRealtimeRequestSessionModality(item.GetString())); - } - modalities = array; + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("voice"u8)) { - instructions = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + voice = new ConversationVoice(prop.Value.GetString()); continue; } - if (property.NameEquals("voice"u8)) + if (prop.NameEquals("input_audio_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - voice = new ConversationVoice(property.Value.GetString()); + inputAudioFormat = new ConversationAudioFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("input_audio_format"u8)) + if (prop.NameEquals("output_audio_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - inputAudioFormat = new ConversationAudioFormat(property.Value.GetString()); + outputAudioFormat = new ConversationAudioFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("output_audio_format"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - outputAudioFormat = new ConversationAudioFormat(property.Value.GetString()); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationTool.DeserializeConversationTool(item, options)); + } + tools = array; continue; } - if (property.NameEquals("input_audio_transcription"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - inputAudioTranscription = null; continue; } - inputAudioTranscription = ConversationInputTranscriptionOptions.DeserializeConversationInputTranscriptionOptions(property.Value, options); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("turn_detection"u8)) + if (prop.NameEquals("turn_detection"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - turnDetection = null; + turnDetectionOptions = null; continue; } - turnDetection = ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(property.Value, options); + turnDetectionOptions = ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(prop.Value, options); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("input_audio_transcription"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + inputTranscriptionOptions = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationTool.DeserializeConversationTool(item, options)); - } - tools = array; + inputTranscriptionOptions = ConversationInputTranscriptionOptions.DeserializeConversationInputTranscriptionOptions(prop.Value, options); continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("modalities"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - toolChoice = BinaryData.FromString(property.Value.GetRawText()); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(new InternalRealtimeRequestSessionModality(item.GetString())); + } + internalModalities = array; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("tool_choice"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - temperature = property.Value.GetSingle(); + internalToolChoice = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("max_response_output_tokens"u8)) + if (prop.NameEquals("max_response_output_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - maxResponseOutputTokens = BinaryData.FromString(property.Value.GetRawText()); + maxResponseOutputTokens = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationSessionOptions( - modalities ?? new ChangeTrackingList(), instructions, voice, inputAudioFormat, outputAudioFormat, - inputAudioTranscription, - turnDetection, tools ?? new ChangeTrackingList(), - toolChoice, temperature, + turnDetectionOptions, + inputTranscriptionOptions, + internalModalities, + internalToolChoice, maxResponseOutputTokens, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -313,15 +315,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - ConversationSessionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationSessionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationSessionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationSessionOptions(document.RootElement, options); } default: @@ -331,15 +334,20 @@ ConversationSessionOptions IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationSessionOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationSessionOptions conversationSessionOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationSessionOptions(document.RootElement); + if (conversationSessionOptions == null) + { + return null; + } + return BinaryContent.Create(conversationSessionOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationSessionOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationSessionOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationSessionOptions.cs b/src/Generated/Models/ConversationSessionOptions.cs index ae6e86ae6..7cf4e0ef0 100644 --- a/src/Generated/Models/ConversationSessionOptions.cs +++ b/src/Generated/Models/ConversationSessionOptions.cs @@ -4,38 +4,52 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationSessionOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ConversationSessionOptions() { - _internalModalities = new ChangeTrackingList(); Tools = new ChangeTrackingList(); + _internalModalities = new ChangeTrackingList(); } - internal ConversationSessionOptions(IList internalModalities, string instructions, ConversationVoice? voice, ConversationAudioFormat? inputAudioFormat, ConversationAudioFormat? outputAudioFormat, ConversationInputTranscriptionOptions inputTranscriptionOptions, ConversationTurnDetectionOptions turnDetectionOptions, IList tools, BinaryData internalToolChoice, float? temperature, BinaryData maxResponseOutputTokens, IDictionary serializedAdditionalRawData) + internal ConversationSessionOptions(string instructions, ConversationVoice? voice, ConversationAudioFormat? inputAudioFormat, ConversationAudioFormat? outputAudioFormat, IList tools, float? temperature, ConversationTurnDetectionOptions turnDetectionOptions, ConversationInputTranscriptionOptions inputTranscriptionOptions, IList internalModalities, BinaryData internalToolChoice, BinaryData maxResponseOutputTokens, IDictionary additionalBinaryDataProperties) { - _internalModalities = internalModalities; Instructions = instructions; Voice = voice; InputAudioFormat = inputAudioFormat; OutputAudioFormat = outputAudioFormat; - InputTranscriptionOptions = inputTranscriptionOptions; - TurnDetectionOptions = turnDetectionOptions; Tools = tools; - _internalToolChoice = internalToolChoice; Temperature = temperature; + TurnDetectionOptions = turnDetectionOptions; + InputTranscriptionOptions = inputTranscriptionOptions; + _internalModalities = internalModalities; + _internalToolChoice = internalToolChoice; _maxResponseOutputTokens = maxResponseOutputTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Instructions { get; set; } + public ConversationVoice? Voice { get; set; } + public ConversationAudioFormat? InputAudioFormat { get; set; } + public ConversationAudioFormat? OutputAudioFormat { get; set; } + public IList Tools { get; } + public float? Temperature { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationSessionStartedUpdate.Serialization.cs b/src/Generated/Models/ConversationSessionStartedUpdate.Serialization.cs index cc55fda4d..af0750875 100644 --- a/src/Generated/Models/ConversationSessionStartedUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationSessionStartedUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationSessionStartedUpdate : IJsonModel { + internal ConversationSessionStartedUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationSessionStartedUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("session") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("session") != true) { writer.WritePropertyName("session"u8); writer.WriteObjectValue(_internalSession, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - ConversationSessionStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationSessionStartedUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ConversationSessionStartedUpdate)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationSessionStartedUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationSessionStartedUpdate(document.RootElement, options); } - internal static ConversationSessionStartedUpdate DeserializeConversationSessionStartedUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationSessionStartedUpdate DeserializeConversationSessionStartedUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeResponseSession session = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeResponseSession internalSession = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("session"u8)) + if (prop.NameEquals("event_id"u8)) { - session = InternalRealtimeResponseSession.DeserializeInternalRealtimeResponseSession(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("session"u8)) { - eventId = property.Value.GetString(); + internalSession = InternalRealtimeResponseSession.DeserializeInternalRealtimeResponseSession(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ConversationSessionStartedUpdate(type, eventId, serializedAdditionalRawData, session); + return new ConversationSessionStartedUpdate(eventId, kind, additionalBinaryDataProperties, internalSession); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - ConversationSessionStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationSessionStartedUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ConversationSessionStartedUpdate)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationSessionStartedUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ ConversationSessionStartedUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ConversationSessionStartedUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationSessionStartedUpdate conversationSessionStartedUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationSessionStartedUpdate(document.RootElement); + if (conversationSessionStartedUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationSessionStartedUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ConversationSessionStartedUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationSessionStartedUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationSessionStartedUpdate.cs b/src/Generated/Models/ConversationSessionStartedUpdate.cs index 3df315521..e3dda4abc 100644 --- a/src/Generated/Models/ConversationSessionStartedUpdate.cs +++ b/src/Generated/Models/ConversationSessionStartedUpdate.cs @@ -9,22 +9,14 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationSessionStartedUpdate : ConversationUpdate { - internal ConversationSessionStartedUpdate(string eventId, InternalRealtimeResponseSession internalSession) : base(eventId) + internal ConversationSessionStartedUpdate(string eventId, InternalRealtimeResponseSession internalSession) : base(eventId, RealtimeConversation.ConversationUpdateKind.SessionStarted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(internalSession, nameof(internalSession)); - - Kind = ConversationUpdateKind.SessionStarted; _internalSession = internalSession; } - internal ConversationSessionStartedUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeResponseSession internalSession) : base(kind, eventId, serializedAdditionalRawData) + internal ConversationSessionStartedUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeResponseSession internalSession) : base(eventId, kind, additionalBinaryDataProperties) { _internalSession = internalSession; } - - internal ConversationSessionStartedUpdate() - { - } } } diff --git a/src/Generated/Models/ConversationStatus.cs b/src/Generated/Models/ConversationStatus.cs index 7de858fc2..d08d9ebbc 100644 --- a/src/Generated/Models/ConversationStatus.cs +++ b/src/Generated/Models/ConversationStatus.cs @@ -4,39 +4,50 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationStatus : IEquatable { private readonly string _value; - - public ConversationStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string InProgressValue = "in_progress"; private const string CompletedValue = "completed"; private const string CancelledValue = "cancelled"; private const string IncompleteValue = "incomplete"; private const string FailedValue = "failed"; + public ConversationStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static ConversationStatus InProgress { get; } = new ConversationStatus(InProgressValue); + public static ConversationStatus Completed { get; } = new ConversationStatus(CompletedValue); + public static ConversationStatus Cancelled { get; } = new ConversationStatus(CancelledValue); + public static ConversationStatus Incomplete { get; } = new ConversationStatus(IncompleteValue); + public static ConversationStatus Failed { get; } = new ConversationStatus(FailedValue); + public static bool operator ==(ConversationStatus left, ConversationStatus right) => left.Equals(right); + public static bool operator !=(ConversationStatus left, ConversationStatus right) => !left.Equals(right); + public static implicit operator ConversationStatus(string value) => new ConversationStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationStatus other && Equals(other); + public bool Equals(ConversationStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationStatusDetails.Serialization.cs b/src/Generated/Models/ConversationStatusDetails.Serialization.cs index 02ca1eaa4..7aabd5019 100644 --- a/src/Generated/Models/ConversationStatusDetails.Serialization.cs +++ b/src/Generated/Models/ConversationStatusDetails.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeResponseStatusDetails))] - public partial class ConversationStatusDetails : IJsonModel + public abstract partial class ConversationStatusDetails : IJsonModel { + internal ConversationStatusDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationStatusDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(StatusKind.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,25 +55,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - ConversationStatusDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationStatusDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationStatusDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationStatusDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationStatusDetails(document.RootElement, options); } - internal static ConversationStatusDetails DeserializeConversationStatusDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationStatusDetails DeserializeConversationStatusDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -71,10 +79,11 @@ internal static ConversationStatusDetails DeserializeConversationStatusDetails(J return UnknownRealtimeResponseStatusDetails.DeserializeUnknownRealtimeResponseStatusDetails(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -84,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - ConversationStatusDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationStatusDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationStatusDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationStatusDetails(document.RootElement, options); } default: @@ -102,15 +112,20 @@ ConversationStatusDetails IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationStatusDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationStatusDetails conversationStatusDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationStatusDetails(document.RootElement); + if (conversationStatusDetails == null) + { + return null; + } + return BinaryContent.Create(conversationStatusDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationStatusDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationStatusDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationStatusDetails.cs b/src/Generated/Models/ConversationStatusDetails.cs index 46056c9ce..1b560fe8d 100644 --- a/src/Generated/Models/ConversationStatusDetails.cs +++ b/src/Generated/Models/ConversationStatusDetails.cs @@ -9,15 +9,23 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationStatusDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationStatusDetails() + private protected IDictionary _additionalBinaryDataProperties; + + private protected ConversationStatusDetails(ConversationStatus statusKind) { + StatusKind = statusKind; } - internal ConversationStatusDetails(ConversationStatus statusKind, IDictionary serializedAdditionalRawData) + internal ConversationStatusDetails(ConversationStatus statusKind, IDictionary additionalBinaryDataProperties) { StatusKind = statusKind; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ConversationTokenUsage.Serialization.cs b/src/Generated/Models/ConversationTokenUsage.Serialization.cs index 4485af275..04a8e335f 100644 --- a/src/Generated/Models/ConversationTokenUsage.Serialization.cs +++ b/src/Generated/Models/ConversationTokenUsage.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { public partial class ConversationTokenUsage : IJsonModel { + internal ConversationTokenUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationTokenUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokens); } - if (SerializedAdditionalRawData?.ContainsKey("input_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_tokens") != true) { writer.WritePropertyName("input_tokens"u8); writer.WriteNumberValue(InputTokens); } - if (SerializedAdditionalRawData?.ContainsKey("output_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_tokens") != true) { writer.WritePropertyName("output_tokens"u8); writer.WriteNumberValue(OutputTokens); } - if (SerializedAdditionalRawData?.ContainsKey("input_token_details") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_token_details") != true) { writer.WritePropertyName("input_token_details"u8); writer.WriteObjectValue(InputTokenDetails, options); } - if (SerializedAdditionalRawData?.ContainsKey("output_token_details") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_token_details") != true) { writer.WritePropertyName("output_token_details"u8); writer.WriteObjectValue(OutputTokenDetails, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,25 +75,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader #endif } } - writer.WriteEndObject(); } - ConversationTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationTokenUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationTokenUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationTokenUsage(document.RootElement, options); } - internal static ConversationTokenUsage DeserializeConversationTokenUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationTokenUsage DeserializeConversationTokenUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -93,55 +101,53 @@ internal static ConversationTokenUsage DeserializeConversationTokenUsage(JsonEle int outputTokens = default; ConversationInputTokenUsageDetails inputTokenDetails = default; ConversationOutputTokenUsageDetails outputTokenDetails = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("input_tokens"u8)) + if (prop.NameEquals("input_tokens"u8)) { - inputTokens = property.Value.GetInt32(); + inputTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("output_tokens"u8)) + if (prop.NameEquals("output_tokens"u8)) { - outputTokens = property.Value.GetInt32(); + outputTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("input_token_details"u8)) + if (prop.NameEquals("input_token_details"u8)) { - inputTokenDetails = ConversationInputTokenUsageDetails.DeserializeConversationInputTokenUsageDetails(property.Value, options); + inputTokenDetails = ConversationInputTokenUsageDetails.DeserializeConversationInputTokenUsageDetails(prop.Value, options); continue; } - if (property.NameEquals("output_token_details"u8)) + if (prop.NameEquals("output_token_details"u8)) { - outputTokenDetails = ConversationOutputTokenUsageDetails.DeserializeConversationOutputTokenUsageDetails(property.Value, options); + outputTokenDetails = ConversationOutputTokenUsageDetails.DeserializeConversationOutputTokenUsageDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ConversationTokenUsage( totalTokens, inputTokens, outputTokens, inputTokenDetails, outputTokenDetails, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +157,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - ConversationTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationTokenUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationTokenUsage(document.RootElement, options); } default: @@ -169,15 +176,20 @@ ConversationTokenUsage IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationTokenUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationTokenUsage conversationTokenUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationTokenUsage(document.RootElement); + if (conversationTokenUsage == null) + { + return null; + } + return BinaryContent.Create(conversationTokenUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationTokenUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationTokenUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationTokenUsage.cs b/src/Generated/Models/ConversationTokenUsage.cs index d8047f775..edc12d4e9 100644 --- a/src/Generated/Models/ConversationTokenUsage.cs +++ b/src/Generated/Models/ConversationTokenUsage.cs @@ -9,12 +9,10 @@ namespace OpenAI.RealtimeConversation { public partial class ConversationTokenUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal ConversationTokenUsage(int totalTokens, int inputTokens, int outputTokens, ConversationInputTokenUsageDetails inputTokenDetails, ConversationOutputTokenUsageDetails outputTokenDetails) { - Argument.AssertNotNull(inputTokenDetails, nameof(inputTokenDetails)); - Argument.AssertNotNull(outputTokenDetails, nameof(outputTokenDetails)); - TotalTokens = totalTokens; InputTokens = inputTokens; OutputTokens = outputTokens; @@ -22,24 +20,30 @@ internal ConversationTokenUsage(int totalTokens, int inputTokens, int outputToke OutputTokenDetails = outputTokenDetails; } - internal ConversationTokenUsage(int totalTokens, int inputTokens, int outputTokens, ConversationInputTokenUsageDetails inputTokenDetails, ConversationOutputTokenUsageDetails outputTokenDetails, IDictionary serializedAdditionalRawData) + internal ConversationTokenUsage(int totalTokens, int inputTokens, int outputTokens, ConversationInputTokenUsageDetails inputTokenDetails, ConversationOutputTokenUsageDetails outputTokenDetails, IDictionary additionalBinaryDataProperties) { TotalTokens = totalTokens; InputTokens = inputTokens; OutputTokens = outputTokens; InputTokenDetails = inputTokenDetails; OutputTokenDetails = outputTokenDetails; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ConversationTokenUsage() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int TotalTokens { get; } + public int InputTokens { get; } + public int OutputTokens { get; } + public ConversationInputTokenUsageDetails InputTokenDetails { get; } + public ConversationOutputTokenUsageDetails OutputTokenDetails { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ConversationTool.Serialization.cs b/src/Generated/Models/ConversationTool.Serialization.cs index c7d7dd0cb..b432b57fd 100644 --- a/src/Generated/Models/ConversationTool.Serialization.cs +++ b/src/Generated/Models/ConversationTool.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeTool))] - public partial class ConversationTool : IJsonModel + public abstract partial class ConversationTool : IJsonModel { + internal ConversationTool() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationTool)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Kind.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,43 +55,43 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - ConversationTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationTool JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationTool)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationTool(document.RootElement, options); } - internal static ConversationTool DeserializeConversationTool(JsonElement element, ModelReaderWriterOptions options = null) + internal static ConversationTool DeserializeConversationTool(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "function": return ConversationFunctionTool.DeserializeConversationFunctionTool(element, options); + case "function": + return ConversationFunctionTool.DeserializeConversationFunctionTool(element, options); } } return UnknownRealtimeTool.DeserializeUnknownRealtimeTool(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -91,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ConversationTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationTool 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationTool(document.RootElement, options); } default: @@ -109,15 +120,20 @@ ConversationTool IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationTool FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationTool conversationTool) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationTool(document.RootElement); + if (conversationTool == null) + { + return null; + } + return BinaryContent.Create(conversationTool, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationTool(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeConversationTool(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationTool.cs b/src/Generated/Models/ConversationTool.cs index fb66af814..3e74df570 100644 --- a/src/Generated/Models/ConversationTool.cs +++ b/src/Generated/Models/ConversationTool.cs @@ -9,15 +9,23 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationTool { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationTool() + private protected IDictionary _additionalBinaryDataProperties; + + private protected ConversationTool(ConversationToolKind kind) { + Kind = kind; } - internal ConversationTool(ConversationToolKind kind, IDictionary serializedAdditionalRawData) + internal ConversationTool(ConversationToolKind kind, IDictionary additionalBinaryDataProperties) { Kind = kind; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ConversationToolChoiceKind.Serialization.cs b/src/Generated/Models/ConversationToolChoiceKind.Serialization.cs index 880cf9f3c..4d7f2010d 100644 --- a/src/Generated/Models/ConversationToolChoiceKind.Serialization.cs +++ b/src/Generated/Models/ConversationToolChoiceKind.Serialization.cs @@ -8,19 +8,28 @@ namespace OpenAI.RealtimeConversation { internal static partial class ConversationToolChoiceKindExtensions { - public static string ToSerialString(this ConversationToolChoiceKind value) => value switch + public static string ToSerialString(this RealtimeConversation.ConversationToolChoiceKind value) => value switch { - ConversationToolChoiceKind.Auto => "auto", - ConversationToolChoiceKind.None => "none", - ConversationToolChoiceKind.Required => "required", + RealtimeConversation.ConversationToolChoiceKind.Auto => "auto", + RealtimeConversation.ConversationToolChoiceKind.None => "none", + RealtimeConversation.ConversationToolChoiceKind.Required => "required", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ConversationToolChoiceKind value.") }; - public static ConversationToolChoiceKind ToConversationToolChoiceKind(this string value) + public static RealtimeConversation.ConversationToolChoiceKind ToConversationToolChoiceKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "auto")) return ConversationToolChoiceKind.Auto; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "none")) return ConversationToolChoiceKind.None; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "required")) return ConversationToolChoiceKind.Required; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "auto")) + { + return RealtimeConversation.ConversationToolChoiceKind.Auto; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "none")) + { + return RealtimeConversation.ConversationToolChoiceKind.None; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "required")) + { + return RealtimeConversation.ConversationToolChoiceKind.Required; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ConversationToolChoiceKind value."); } } diff --git a/src/Generated/Models/ConversationToolKind.cs b/src/Generated/Models/ConversationToolKind.cs index acb65bef4..64f0a0eea 100644 --- a/src/Generated/Models/ConversationToolKind.cs +++ b/src/Generated/Models/ConversationToolKind.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationToolKind : IEquatable { private readonly string _value; + private const string FunctionValue = "function"; public ConversationToolKind(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FunctionValue = "function"; + _value = value; + } public static ConversationToolKind Function { get; } = new ConversationToolKind(FunctionValue); + public static bool operator ==(ConversationToolKind left, ConversationToolKind right) => left.Equals(right); + public static bool operator !=(ConversationToolKind left, ConversationToolKind right) => !left.Equals(right); + public static implicit operator ConversationToolKind(string value) => new ConversationToolKind(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationToolKind other && Equals(other); + public bool Equals(ConversationToolKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationTranscriptionModel.cs b/src/Generated/Models/ConversationTranscriptionModel.cs index 37d47426a..1b81388c4 100644 --- a/src/Generated/Models/ConversationTranscriptionModel.cs +++ b/src/Generated/Models/ConversationTranscriptionModel.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationTranscriptionModel : IEquatable { private readonly string _value; + private const string Whisper1Value = "whisper-1"; public ConversationTranscriptionModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Whisper1Value = "whisper-1"; + _value = value; + } public static ConversationTranscriptionModel Whisper1 { get; } = new ConversationTranscriptionModel(Whisper1Value); + public static bool operator ==(ConversationTranscriptionModel left, ConversationTranscriptionModel right) => left.Equals(right); + public static bool operator !=(ConversationTranscriptionModel left, ConversationTranscriptionModel right) => !left.Equals(right); + public static implicit operator ConversationTranscriptionModel(string value) => new ConversationTranscriptionModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationTranscriptionModel other && Equals(other); + public bool Equals(ConversationTranscriptionModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ConversationTurnDetectionKind.Serialization.cs b/src/Generated/Models/ConversationTurnDetectionKind.Serialization.cs index c2efd47d7..fd991f4c0 100644 --- a/src/Generated/Models/ConversationTurnDetectionKind.Serialization.cs +++ b/src/Generated/Models/ConversationTurnDetectionKind.Serialization.cs @@ -8,15 +8,18 @@ namespace OpenAI.RealtimeConversation { internal static partial class ConversationTurnDetectionKindExtensions { - public static string ToSerialString(this ConversationTurnDetectionKind value) => value switch + public static string ToSerialString(this RealtimeConversation.ConversationTurnDetectionKind value) => value switch { - ConversationTurnDetectionKind.ServerVoiceActivityDetection => "server_vad", + RealtimeConversation.ConversationTurnDetectionKind.ServerVoiceActivityDetection => "server_vad", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ConversationTurnDetectionKind value.") }; - public static ConversationTurnDetectionKind ToConversationTurnDetectionKind(this string value) + public static RealtimeConversation.ConversationTurnDetectionKind ToConversationTurnDetectionKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "server_vad")) return ConversationTurnDetectionKind.ServerVoiceActivityDetection; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "server_vad")) + { + return RealtimeConversation.ConversationTurnDetectionKind.ServerVoiceActivityDetection; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ConversationTurnDetectionKind value."); } } diff --git a/src/Generated/Models/ConversationTurnDetectionOptions.Serialization.cs b/src/Generated/Models/ConversationTurnDetectionOptions.Serialization.cs index 649f6f784..d308a20ee 100644 --- a/src/Generated/Models/ConversationTurnDetectionOptions.Serialization.cs +++ b/src/Generated/Models/ConversationTurnDetectionOptions.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeTurnDetection))] - public partial class ConversationTurnDetectionOptions : IJsonModel + public abstract partial class ConversationTurnDetectionOptions : IJsonModel { + internal ConversationTurnDetectionOptions() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationTurnDetectionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Kind.ToSerialString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,25 +55,26 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - ConversationTurnDetectionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationTurnDetectionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationTurnDetectionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationTurnDetectionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeConversationTurnDetectionOptions(document.RootElement, options); + return ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -73,16 +84,17 @@ BinaryData IPersistableModel.Write(ModelReader } } - ConversationTurnDetectionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationTurnDetectionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationTurnDetectionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeConversationTurnDetectionOptions(document.RootElement, options); + return ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ConversationTurnDetectionOptions)} does not support reading '{options.Format}' format."); @@ -91,15 +103,20 @@ ConversationTurnDetectionOptions IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationTurnDetectionOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationTurnDetectionOptions conversationTurnDetectionOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationTurnDetectionOptions(document.RootElement); + if (conversationTurnDetectionOptions == null) + { + return null; + } + return BinaryContent.Create(conversationTurnDetectionOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationTurnDetectionOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationTurnDetectionOptions.cs b/src/Generated/Models/ConversationTurnDetectionOptions.cs index 1349c2772..bf1534995 100644 --- a/src/Generated/Models/ConversationTurnDetectionOptions.cs +++ b/src/Generated/Models/ConversationTurnDetectionOptions.cs @@ -9,15 +9,23 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationTurnDetectionOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationTurnDetectionOptions() + private protected IDictionary _additionalBinaryDataProperties; + + private protected ConversationTurnDetectionOptions(RealtimeConversation.ConversationTurnDetectionKind kind) { + Kind = kind; } - internal ConversationTurnDetectionOptions(ConversationTurnDetectionKind kind, IDictionary serializedAdditionalRawData) + internal ConversationTurnDetectionOptions(RealtimeConversation.ConversationTurnDetectionKind kind, IDictionary additionalBinaryDataProperties) { Kind = kind; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ConversationUpdate.Serialization.cs b/src/Generated/Models/ConversationUpdate.Serialization.cs index 26aad8972..e1256ed33 100644 --- a/src/Generated/Models/ConversationUpdate.Serialization.cs +++ b/src/Generated/Models/ConversationUpdate.Serialization.cs @@ -6,34 +6,44 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeServerEvent))] - public partial class ConversationUpdate : IJsonModel + public abstract partial class ConversationUpdate : IJsonModel { + internal ConversationUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("event_id") != true) { writer.WritePropertyName("event_id"u8); writer.WriteStringValue(EventId); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,25 +60,26 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - ConversationUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeConversationUpdate(document.RootElement, options); + return ConversationUpdate.DeserializeConversationUpdate(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -78,16 +89,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ConversationUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeConversationUpdate(document.RootElement, options); + return ConversationUpdate.DeserializeConversationUpdate(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ConversationUpdate)} does not support reading '{options.Format}' format."); @@ -96,15 +108,20 @@ ConversationUpdate IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ConversationUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ConversationUpdate conversationUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeConversationUpdate(document.RootElement); + if (conversationUpdate == null) + { + return null; + } + return BinaryContent.Create(conversationUpdate, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ConversationUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ConversationUpdate.DeserializeConversationUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ConversationUpdate.cs b/src/Generated/Models/ConversationUpdate.cs index 5ba9b14fc..75eb30dc3 100644 --- a/src/Generated/Models/ConversationUpdate.cs +++ b/src/Generated/Models/ConversationUpdate.cs @@ -9,24 +9,27 @@ namespace OpenAI.RealtimeConversation { public abstract partial class ConversationUpdate { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ConversationUpdate(string eventId) - { - Argument.AssertNotNull(eventId, nameof(eventId)); + private protected IDictionary _additionalBinaryDataProperties; + private protected ConversationUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind) + { EventId = eventId; + Kind = kind; } - internal ConversationUpdate(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData) + internal ConversationUpdate(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties) { - Kind = kind; EventId = eventId; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ConversationUpdate() + public string EventId { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public string EventId { get; } } } diff --git a/src/Generated/Models/ConversationUpdateKind.Serialization.cs b/src/Generated/Models/ConversationUpdateKind.Serialization.cs index 392ccad40..f86fbce70 100644 --- a/src/Generated/Models/ConversationUpdateKind.Serialization.cs +++ b/src/Generated/Models/ConversationUpdateKind.Serialization.cs @@ -2,8 +2,6 @@ #nullable disable -using System; - namespace OpenAI.RealtimeConversation { internal static partial class ConversationUpdateKindExtensions diff --git a/src/Generated/Models/ConversationVoice.cs b/src/Generated/Models/ConversationVoice.cs index 1c845699c..20419d714 100644 --- a/src/Generated/Models/ConversationVoice.cs +++ b/src/Generated/Models/ConversationVoice.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { public readonly partial struct ConversationVoice : IEquatable { private readonly string _value; + private const string AlloyValue = "alloy"; + private const string ShimmerValue = "shimmer"; + private const string EchoValue = "echo"; public ConversationVoice(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AlloyValue = "alloy"; - private const string ShimmerValue = "shimmer"; - private const string EchoValue = "echo"; + _value = value; + } public static ConversationVoice Alloy { get; } = new ConversationVoice(AlloyValue); + public static ConversationVoice Shimmer { get; } = new ConversationVoice(ShimmerValue); + public static ConversationVoice Echo { get; } = new ConversationVoice(EchoValue); + public static bool operator ==(ConversationVoice left, ConversationVoice right) => left.Equals(right); + public static bool operator !=(ConversationVoice left, ConversationVoice right) => !left.Equals(right); + public static implicit operator ConversationVoice(string value) => new ConversationVoice(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ConversationVoice other && Equals(other); + public bool Equals(ConversationVoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/EmbeddingGenerationOptions.Serialization.cs b/src/Generated/Models/EmbeddingGenerationOptions.Serialization.cs index 5a2ee5c11..c71be3f7c 100644 --- a/src/Generated/Models/EmbeddingGenerationOptions.Serialization.cs +++ b/src/Generated/Models/EmbeddingGenerationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Embeddings { @@ -14,18 +15,28 @@ public partial class EmbeddingGenerationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(EmbeddingGenerationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("input") != true) + if (Optional.IsDefined(Dimensions) && _additionalBinaryDataProperties?.ContainsKey("dimensions") != true) + { + writer.WritePropertyName("dimensions"u8); + writer.WriteNumberValue(Dimensions.Value); + } + if (_additionalBinaryDataProperties?.ContainsKey("input") != true) { writer.WritePropertyName("input"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(Input); + writer.WriteRawValue(Input); #else using (JsonDocument document = JsonDocument.Parse(Input)) { @@ -33,29 +44,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } #endif } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("encoding_format") != true && Optional.IsDefined(EncodingFormat)) + if (Optional.IsDefined(EncodingFormat) && _additionalBinaryDataProperties?.ContainsKey("encoding_format") != true) { writer.WritePropertyName("encoding_format"u8); writer.WriteStringValue(EncodingFormat.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("dimensions") != true && Optional.IsDefined(Dimensions)) - { - writer.WritePropertyName("dimensions"u8); - writer.WriteNumberValue(Dimensions.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) + if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true) { writer.WritePropertyName("user"u8); writer.WriteStringValue(EndUserId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -63,7 +69,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -72,91 +78,87 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - EmbeddingGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + EmbeddingGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual EmbeddingGenerationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(EmbeddingGenerationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeEmbeddingGenerationOptions(document.RootElement, options); } - internal static EmbeddingGenerationOptions DeserializeEmbeddingGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static EmbeddingGenerationOptions DeserializeEmbeddingGenerationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + int? dimensions = default; BinaryData input = default; InternalCreateEmbeddingRequestModel model = default; InternalCreateEmbeddingRequestEncodingFormat? encodingFormat = default; - int? dimensions = default; - string user = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string endUserId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("input"u8)) + if (prop.NameEquals("dimensions"u8)) { - input = BinaryData.FromString(property.Value.GetRawText()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dimensions = prop.Value.GetInt32(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("input"u8)) { - model = new InternalCreateEmbeddingRequestModel(property.Value.GetString()); + input = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("encoding_format"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - encodingFormat = new InternalCreateEmbeddingRequestEncodingFormat(property.Value.GetString()); + model = new InternalCreateEmbeddingRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("dimensions"u8)) + if (prop.NameEquals("encoding_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - dimensions = property.Value.GetInt32(); + encodingFormat = new InternalCreateEmbeddingRequestEncodingFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("user"u8)) { - user = property.Value.GetString(); + endUserId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new EmbeddingGenerationOptions( + dimensions, input, model, encodingFormat, - dimensions, - user, - serializedAdditionalRawData); + endUserId, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -166,15 +168,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - EmbeddingGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + EmbeddingGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual EmbeddingGenerationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeEmbeddingGenerationOptions(document.RootElement, options); } default: @@ -184,15 +187,20 @@ EmbeddingGenerationOptions IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static EmbeddingGenerationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(EmbeddingGenerationOptions embeddingGenerationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeEmbeddingGenerationOptions(document.RootElement); + if (embeddingGenerationOptions == null) + { + return null; + } + return BinaryContent.Create(embeddingGenerationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator EmbeddingGenerationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeEmbeddingGenerationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/EmbeddingGenerationOptions.cs b/src/Generated/Models/EmbeddingGenerationOptions.cs index 92ffbca28..00ac24783 100644 --- a/src/Generated/Models/EmbeddingGenerationOptions.cs +++ b/src/Generated/Models/EmbeddingGenerationOptions.cs @@ -9,17 +9,24 @@ namespace OpenAI.Embeddings { public partial class EmbeddingGenerationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal EmbeddingGenerationOptions(BinaryData input, InternalCreateEmbeddingRequestModel model, InternalCreateEmbeddingRequestEncodingFormat? encodingFormat, int? dimensions, string endUserId, IDictionary serializedAdditionalRawData) + internal EmbeddingGenerationOptions(int? dimensions, BinaryData input, InternalCreateEmbeddingRequestModel model, InternalCreateEmbeddingRequestEncodingFormat? encodingFormat, string endUserId, IDictionary additionalBinaryDataProperties) { + Dimensions = dimensions; Input = input; Model = model; EncodingFormat = encodingFormat; - Dimensions = dimensions; EndUserId = endUserId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public int? Dimensions { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs b/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs index ae3a15612..49f4c9685 100644 --- a/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs +++ b/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Embeddings { public partial class EmbeddingTokenUsage : IJsonModel { + internal EmbeddingTokenUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(EmbeddingTokenUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); writer.WriteNumberValue(InputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokenCount); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri #endif } } - writer.WriteEndObject(); } - EmbeddingTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + EmbeddingTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual EmbeddingTokenUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(EmbeddingTokenUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeEmbeddingTokenUsage(document.RootElement, options); } - internal static EmbeddingTokenUsage DeserializeEmbeddingTokenUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static EmbeddingTokenUsage DeserializeEmbeddingTokenUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int promptTokens = default; - int totalTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int inputTokenCount = default; + int totalTokenCount = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("prompt_tokens"u8)) + if (prop.NameEquals("prompt_tokens"u8)) { - promptTokens = property.Value.GetInt32(); + inputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokenCount = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new EmbeddingTokenUsage(promptTokens, totalTokens, serializedAdditionalRawData); + return new EmbeddingTokenUsage(inputTokenCount, totalTokenCount, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - EmbeddingTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + EmbeddingTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual EmbeddingTokenUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeEmbeddingTokenUsage(document.RootElement, options); } default: @@ -130,15 +137,20 @@ EmbeddingTokenUsage IPersistableModel.Create(BinaryData dat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static EmbeddingTokenUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(EmbeddingTokenUsage embeddingTokenUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeEmbeddingTokenUsage(document.RootElement); + if (embeddingTokenUsage == null) + { + return null; + } + return BinaryContent.Create(embeddingTokenUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator EmbeddingTokenUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeEmbeddingTokenUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/EmbeddingTokenUsage.cs b/src/Generated/Models/EmbeddingTokenUsage.cs index ab5e300dc..4d3b185c2 100644 --- a/src/Generated/Models/EmbeddingTokenUsage.cs +++ b/src/Generated/Models/EmbeddingTokenUsage.cs @@ -9,22 +9,25 @@ namespace OpenAI.Embeddings { public partial class EmbeddingTokenUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal EmbeddingTokenUsage(int inputTokenCount, int totalTokenCount) { InputTokenCount = inputTokenCount; TotalTokenCount = totalTokenCount; } - internal EmbeddingTokenUsage(int inputTokenCount, int totalTokenCount, IDictionary serializedAdditionalRawData) + internal EmbeddingTokenUsage(int inputTokenCount, int totalTokenCount, IDictionary additionalBinaryDataProperties) { InputTokenCount = inputTokenCount; TotalTokenCount = totalTokenCount; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal EmbeddingTokenUsage() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/FileChunkingStrategy.Serialization.cs b/src/Generated/Models/FileChunkingStrategy.Serialization.cs index c56c5329a..42ed82c29 100644 --- a/src/Generated/Models/FileChunkingStrategy.Serialization.cs +++ b/src/Generated/Models/FileChunkingStrategy.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { [PersistableModelProxy(typeof(InternalUnknownFileChunkingStrategyResponseParamProxy))] - public partial class FileChunkingStrategy : IJsonModel + public abstract partial class FileChunkingStrategy : IJsonModel { + internal FileChunkingStrategy() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileChunkingStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,45 +55,47 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr #endif } } - writer.WriteEndObject(); } - FileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileChunkingStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileChunkingStrategy(document.RootElement, options); } - internal static FileChunkingStrategy DeserializeFileChunkingStrategy(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileChunkingStrategy DeserializeFileChunkingStrategy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "auto": return InternalAutoChunkingStrategy.DeserializeInternalAutoChunkingStrategy(element, options); - case "other": return InternalUnknownChunkingStrategy.DeserializeInternalUnknownChunkingStrategy(element, options); - case "static": return StaticFileChunkingStrategy.DeserializeStaticFileChunkingStrategy(element, options); + case "static": + return StaticFileChunkingStrategy.DeserializeStaticFileChunkingStrategy(element, options); + case "other": + return InternalUnknownChunkingStrategy.DeserializeInternalUnknownChunkingStrategy(element, options); + case "auto": + return InternalAutoChunkingStrategy.DeserializeInternalAutoChunkingStrategy(element, options); } } return InternalUnknownFileChunkingStrategyResponseParamProxy.DeserializeInternalUnknownFileChunkingStrategyResponseParamProxy(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -93,15 +105,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - FileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FileChunkingStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileChunkingStrategy(document.RootElement, options); } default: @@ -111,15 +124,20 @@ FileChunkingStrategy IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FileChunkingStrategy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileChunkingStrategy fileChunkingStrategy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileChunkingStrategy(document.RootElement); + if (fileChunkingStrategy == null) + { + return null; + } + return BinaryContent.Create(fileChunkingStrategy, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FileChunkingStrategy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileChunkingStrategy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileChunkingStrategy.cs b/src/Generated/Models/FileChunkingStrategy.cs index b93a33e99..8d2b27374 100644 --- a/src/Generated/Models/FileChunkingStrategy.cs +++ b/src/Generated/Models/FileChunkingStrategy.cs @@ -9,17 +9,25 @@ namespace OpenAI.VectorStores { public abstract partial class FileChunkingStrategy { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected FileChunkingStrategy() + private protected IDictionary _additionalBinaryDataProperties; + + private protected FileChunkingStrategy(string @type) { + Type = @type; } - internal FileChunkingStrategy(string type, IDictionary serializedAdditionalRawData) + internal FileChunkingStrategy(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FileDeletionResult.Serialization.cs b/src/Generated/Models/FileDeletionResult.Serialization.cs index 6a51e8406..455776386 100644 --- a/src/Generated/Models/FileDeletionResult.Serialization.cs +++ b/src/Generated/Models/FileDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { public partial class FileDeletionResult : IJsonModel { + internal FileDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) + { + writer.WritePropertyName("deleted"u8); + writer.WriteBooleanValue(Deleted); + } + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (true && _additionalBinaryDataProperties != null) { - writer.WritePropertyName("deleted"u8); - writer.WriteBooleanValue(Deleted); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - FileDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FileDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileDeletionResult(document.RootElement, options); } - internal static FileDeletionResult DeserializeFileDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileDeletionResult DeserializeFileDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; - InternalDeleteFileResponseObject @object = default; bool deleted = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string fileId = default; + InternalDeleteFileResponseObject @object = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalDeleteFileResponseObject(property.Value.GetString()); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("object"u8)) { - deleted = property.Value.GetBoolean(); + @object = new InternalDeleteFileResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FileDeletionResult(id, @object, deleted, serializedAdditionalRawData); + return new FileDeletionResult(deleted, fileId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - FileDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FileDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ FileDeletionResult IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FileDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileDeletionResult fileDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileDeletionResult(document.RootElement); + if (fileDeletionResult == null) + { + return null; + } + return BinaryContent.Create(fileDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FileDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileDeletionResult.cs b/src/Generated/Models/FileDeletionResult.cs index 55bab610c..a5b822c49 100644 --- a/src/Generated/Models/FileDeletionResult.cs +++ b/src/Generated/Models/FileDeletionResult.cs @@ -9,27 +9,28 @@ namespace OpenAI.Files { public partial class FileDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal FileDeletionResult(string fileId, bool deleted) - { - Argument.AssertNotNull(fileId, nameof(fileId)); + private protected IDictionary _additionalBinaryDataProperties; - FileId = fileId; + internal FileDeletionResult(bool deleted, string fileId) + { Deleted = deleted; + FileId = fileId; } - internal FileDeletionResult(string fileId, InternalDeleteFileResponseObject @object, bool deleted, IDictionary serializedAdditionalRawData) + internal FileDeletionResult(bool deleted, string fileId, InternalDeleteFileResponseObject @object, IDictionary additionalBinaryDataProperties) { - FileId = fileId; - Object = @object; Deleted = deleted; - SerializedAdditionalRawData = serializedAdditionalRawData; + FileId = fileId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal FileDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public bool Deleted { get; } } } diff --git a/src/Generated/Models/FileFromStoreRemovalResult.Serialization.cs b/src/Generated/Models/FileFromStoreRemovalResult.Serialization.cs index a9d34f8fc..fb331ff03 100644 --- a/src/Generated/Models/FileFromStoreRemovalResult.Serialization.cs +++ b/src/Generated/Models/FileFromStoreRemovalResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class FileFromStoreRemovalResult : IJsonModel { + internal FileFromStoreRemovalResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileFromStoreRemovalResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Removed); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - FileFromStoreRemovalResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileFromStoreRemovalResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FileFromStoreRemovalResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileFromStoreRemovalResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileFromStoreRemovalResult(document.RootElement, options); } - internal static FileFromStoreRemovalResult DeserializeFileFromStoreRemovalResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileFromStoreRemovalResult DeserializeFileFromStoreRemovalResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; - bool deleted = default; + string fileId = default; + bool removed = default; InternalDeleteVectorStoreFileResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("deleted"u8)) { - deleted = property.Value.GetBoolean(); + removed = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteVectorStoreFileResponseObject(property.Value.GetString()); + @object = new InternalDeleteVectorStoreFileResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FileFromStoreRemovalResult(id, deleted, @object, serializedAdditionalRawData); + return new FileFromStoreRemovalResult(fileId, removed, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - FileFromStoreRemovalResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileFromStoreRemovalResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FileFromStoreRemovalResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileFromStoreRemovalResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ FileFromStoreRemovalResult IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FileFromStoreRemovalResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileFromStoreRemovalResult fileFromStoreRemovalResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileFromStoreRemovalResult(document.RootElement); + if (fileFromStoreRemovalResult == null) + { + return null; + } + return BinaryContent.Create(fileFromStoreRemovalResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FileFromStoreRemovalResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileFromStoreRemovalResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileFromStoreRemovalResult.cs b/src/Generated/Models/FileFromStoreRemovalResult.cs index 501e1057c..b6d00d34e 100644 --- a/src/Generated/Models/FileFromStoreRemovalResult.cs +++ b/src/Generated/Models/FileFromStoreRemovalResult.cs @@ -9,25 +9,26 @@ namespace OpenAI.VectorStores { public partial class FileFromStoreRemovalResult { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal FileFromStoreRemovalResult(string fileId, bool removed) { - Argument.AssertNotNull(fileId, nameof(fileId)); - FileId = fileId; Removed = removed; } - internal FileFromStoreRemovalResult(string fileId, bool removed, InternalDeleteVectorStoreFileResponseObject @object, IDictionary serializedAdditionalRawData) + internal FileFromStoreRemovalResult(string fileId, bool removed, InternalDeleteVectorStoreFileResponseObject @object, IDictionary additionalBinaryDataProperties) { FileId = fileId; Removed = removed; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal FileFromStoreRemovalResult() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/FilePurpose.Serialization.cs b/src/Generated/Models/FilePurpose.Serialization.cs index 00250272c..2fed310a1 100644 --- a/src/Generated/Models/FilePurpose.Serialization.cs +++ b/src/Generated/Models/FilePurpose.Serialization.cs @@ -8,27 +8,48 @@ namespace OpenAI.Files { internal static partial class FilePurposeExtensions { - public static string ToSerialString(this FilePurpose value) => value switch + public static string ToSerialString(this Files.FilePurpose value) => value switch { - FilePurpose.Assistants => "assistants", - FilePurpose.AssistantsOutput => "assistants_output", - FilePurpose.Batch => "batch", - FilePurpose.BatchOutput => "batch_output", - FilePurpose.FineTune => "fine-tune", - FilePurpose.FineTuneResults => "fine-tune-results", - FilePurpose.Vision => "vision", + Files.FilePurpose.Assistants => "assistants", + Files.FilePurpose.AssistantsOutput => "assistants_output", + Files.FilePurpose.Batch => "batch", + Files.FilePurpose.BatchOutput => "batch_output", + Files.FilePurpose.FineTune => "fine-tune", + Files.FilePurpose.FineTuneResults => "fine-tune-results", + Files.FilePurpose.Vision => "vision", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FilePurpose value.") }; - public static FilePurpose ToFilePurpose(this string value) + public static Files.FilePurpose ToFilePurpose(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistants")) return FilePurpose.Assistants; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistants_output")) return FilePurpose.AssistantsOutput; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "batch")) return FilePurpose.Batch; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "batch_output")) return FilePurpose.BatchOutput; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "fine-tune")) return FilePurpose.FineTune; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "fine-tune-results")) return FilePurpose.FineTuneResults; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "vision")) return FilePurpose.Vision; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistants")) + { + return Files.FilePurpose.Assistants; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistants_output")) + { + return Files.FilePurpose.AssistantsOutput; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "batch")) + { + return Files.FilePurpose.Batch; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "batch_output")) + { + return Files.FilePurpose.BatchOutput; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "fine-tune")) + { + return Files.FilePurpose.FineTune; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "fine-tune-results")) + { + return Files.FilePurpose.FineTuneResults; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "vision")) + { + return Files.FilePurpose.Vision; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FilePurpose value."); } } diff --git a/src/Generated/Models/FileSearchRanker.cs b/src/Generated/Models/FileSearchRanker.cs index a1d8262c4..36ee78fa5 100644 --- a/src/Generated/Models/FileSearchRanker.cs +++ b/src/Generated/Models/FileSearchRanker.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct FileSearchRanker : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string Default20240821Value = "default_2024_08_21"; public FileSearchRanker(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string Default20240821Value = "default_2024_08_21"; + _value = value; + } public static FileSearchRanker Auto { get; } = new FileSearchRanker(AutoValue); + public static FileSearchRanker Default20240821 { get; } = new FileSearchRanker(Default20240821Value); + public static bool operator ==(FileSearchRanker left, FileSearchRanker right) => left.Equals(right); + public static bool operator !=(FileSearchRanker left, FileSearchRanker right) => !left.Equals(right); + public static implicit operator FileSearchRanker(string value) => new FileSearchRanker(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FileSearchRanker other && Equals(other); + public bool Equals(FileSearchRanker other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FileSearchRankingOptions.Serialization.cs b/src/Generated/Models/FileSearchRankingOptions.Serialization.cs index 82356b1f2..04fe002e3 100644 --- a/src/Generated/Models/FileSearchRankingOptions.Serialization.cs +++ b/src/Generated/Models/FileSearchRankingOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ public partial class FileSearchRankingOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileSearchRankingOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("ranker") != true && Optional.IsDefined(Ranker)) + if (Optional.IsDefined(Ranker) && _additionalBinaryDataProperties?.ContainsKey("ranker") != true) { writer.WritePropertyName("ranker"u8); writer.WriteStringValue(Ranker.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("score_threshold") != true) + if (_additionalBinaryDataProperties?.ContainsKey("score_threshold") != true) { writer.WritePropertyName("score_threshold"u8); writer.WriteNumberValue(_scoreThreshold); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,63 +56,59 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead #endif } } - writer.WriteEndObject(); } - FileSearchRankingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileSearchRankingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FileSearchRankingOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileSearchRankingOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileSearchRankingOptions(document.RootElement, options); } - internal static FileSearchRankingOptions DeserializeFileSearchRankingOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileSearchRankingOptions DeserializeFileSearchRankingOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } FileSearchRanker? ranker = default; float scoreThreshold = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("ranker"u8)) + if (prop.NameEquals("ranker"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - ranker = new FileSearchRanker(property.Value.GetString()); + ranker = new FileSearchRanker(prop.Value.GetString()); continue; } - if (property.NameEquals("score_threshold"u8)) + if (prop.NameEquals("score_threshold"u8)) { - scoreThreshold = property.Value.GetSingle(); + scoreThreshold = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FileSearchRankingOptions(ranker, scoreThreshold, serializedAdditionalRawData); + return new FileSearchRankingOptions(ranker, scoreThreshold, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -116,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - FileSearchRankingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileSearchRankingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FileSearchRankingOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileSearchRankingOptions(document.RootElement, options); } default: @@ -134,15 +137,20 @@ FileSearchRankingOptions IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FileSearchRankingOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileSearchRankingOptions fileSearchRankingOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileSearchRankingOptions(document.RootElement); + if (fileSearchRankingOptions == null) + { + return null; + } + return BinaryContent.Create(fileSearchRankingOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FileSearchRankingOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchRankingOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileSearchRankingOptions.cs b/src/Generated/Models/FileSearchRankingOptions.cs index 0a498f2f9..cdcad2aed 100644 --- a/src/Generated/Models/FileSearchRankingOptions.cs +++ b/src/Generated/Models/FileSearchRankingOptions.cs @@ -9,8 +9,14 @@ namespace OpenAI.Assistants { public partial class FileSearchRankingOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; public FileSearchRanker? Ranker { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FileSearchToolDefinition.Serialization.cs b/src/Generated/Models/FileSearchToolDefinition.Serialization.cs index 23868744b..7fc0595e1 100644 --- a/src/Generated/Models/FileSearchToolDefinition.Serialization.cs +++ b/src/Generated/Models/FileSearchToolDefinition.Serialization.cs @@ -7,65 +7,78 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class FileSearchToolDefinition : IJsonModel { - FileSearchToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(_fileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(_fileSearch, options); } + } + + FileSearchToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (FileSearchToolDefinition)JsonModelCreateCore(ref reader, options); + protected override ToolDefinition 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(FileSearchToolDefinition)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileSearchToolDefinition(document.RootElement, options); } - internal static FileSearchToolDefinition DeserializeFileSearchToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileSearchToolDefinition DeserializeFileSearchToolDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_search"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalAssistantToolsFileSearchFileSearch fileSearch = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fileSearch = InternalAssistantToolsFileSearchFileSearch.DeserializeInternalAssistantToolsFileSearchFileSearch(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("file_search"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = InternalAssistantToolsFileSearchFileSearch.DeserializeInternalAssistantToolsFileSearchFileSearch(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FileSearchToolDefinition(type, serializedAdditionalRawData, fileSearch); + return new FileSearchToolDefinition(@type, additionalBinaryDataProperties, fileSearch); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -75,15 +88,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - FileSearchToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileSearchToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (FileSearchToolDefinition)PersistableModelCreateCore(data, options); + protected override ToolDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileSearchToolDefinition(document.RootElement, options); } default: @@ -93,15 +107,20 @@ FileSearchToolDefinition IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new FileSearchToolDefinition FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileSearchToolDefinition fileSearchToolDefinition) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileSearchToolDefinition(document.RootElement); + if (fileSearchToolDefinition == null) + { + return null; + } + return BinaryContent.Create(fileSearchToolDefinition, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator FileSearchToolDefinition(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchToolDefinition(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileSearchToolDefinition.cs b/src/Generated/Models/FileSearchToolDefinition.cs index a91be72a4..1eacf9ff7 100644 --- a/src/Generated/Models/FileSearchToolDefinition.cs +++ b/src/Generated/Models/FileSearchToolDefinition.cs @@ -9,7 +9,7 @@ namespace OpenAI.Assistants { public partial class FileSearchToolDefinition : ToolDefinition { - internal FileSearchToolDefinition(string type, IDictionary serializedAdditionalRawData, InternalAssistantToolsFileSearchFileSearch fileSearch) : base(type, serializedAdditionalRawData) + internal FileSearchToolDefinition(string @type, IDictionary additionalBinaryDataProperties, InternalAssistantToolsFileSearchFileSearch fileSearch) : base(@type, additionalBinaryDataProperties) { _fileSearch = fileSearch; } diff --git a/src/Generated/Models/FileSearchToolResources.Serialization.cs b/src/Generated/Models/FileSearchToolResources.Serialization.cs index 15df3db90..df2ec91f8 100644 --- a/src/Generated/Models/FileSearchToolResources.Serialization.cs +++ b/src/Generated/Models/FileSearchToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,41 @@ public partial class FileSearchToolResources : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileSearchToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) + if (Optional.IsCollectionDefined(VectorStoreIds) && _additionalBinaryDataProperties?.ContainsKey("vector_store_ids") != true) { writer.WritePropertyName("vector_store_ids"u8); writer.WriteStartArray(); - foreach (var item in VectorStoreIds) + foreach (string item in VectorStoreIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("vector_stores") != true && Optional.IsCollectionDefined(NewVectorStores)) + if (Optional.IsCollectionDefined(NewVectorStores) && _additionalBinaryDataProperties?.ContainsKey("vector_stores") != true) { writer.WritePropertyName("vector_stores"u8); - SerializeNewVectorStores(writer, options); + this.SerializeNewVectorStores(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +57,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,77 +66,80 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - FileSearchToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileSearchToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FileSearchToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileSearchToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileSearchToolResources(document.RootElement, options); } - internal static FileSearchToolResources DeserializeFileSearchToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileSearchToolResources DeserializeFileSearchToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList vectorStoreIds = default; - IList vectorStores = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList newVectorStores = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("vector_store_ids"u8)) + if (prop.NameEquals("vector_store_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } vectorStoreIds = array; continue; } - if (property.NameEquals("vector_stores"u8)) + if (prop.NameEquals("vector_stores"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(VectorStoreCreationHelper.DeserializeVectorStoreCreationHelper(item, options)); } - vectorStores = array; + newVectorStores = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FileSearchToolResources(vectorStoreIds ?? new ChangeTrackingList(), vectorStores ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new FileSearchToolResources(vectorStoreIds ?? new ChangeTrackingList(), newVectorStores ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +149,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - FileSearchToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileSearchToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FileSearchToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileSearchToolResources(document.RootElement, options); } default: @@ -153,15 +168,20 @@ FileSearchToolResources IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FileSearchToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FileSearchToolResources fileSearchToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFileSearchToolResources(document.RootElement); + if (fileSearchToolResources == null) + { + return null; + } + return BinaryContent.Create(fileSearchToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FileSearchToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FileSearchToolResources.cs b/src/Generated/Models/FileSearchToolResources.cs index 21ddbd788..7cb29c848 100644 --- a/src/Generated/Models/FileSearchToolResources.cs +++ b/src/Generated/Models/FileSearchToolResources.cs @@ -9,13 +9,19 @@ namespace OpenAI.Assistants { public partial class FileSearchToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal FileSearchToolResources(IList vectorStoreIds, IList newVectorStores, IDictionary serializedAdditionalRawData) + internal FileSearchToolResources(IList vectorStoreIds, IList newVectorStores, IDictionary additionalBinaryDataProperties) { VectorStoreIds = vectorStoreIds; NewVectorStores = newVectorStores; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/FileStatus.Serialization.cs b/src/Generated/Models/FileStatus.Serialization.cs index cee9bafed..cf3193c9f 100644 --- a/src/Generated/Models/FileStatus.Serialization.cs +++ b/src/Generated/Models/FileStatus.Serialization.cs @@ -8,19 +8,28 @@ namespace OpenAI.Files { internal static partial class FileStatusExtensions { - public static string ToSerialString(this FileStatus value) => value switch + public static string ToSerialString(this Files.FileStatus value) => value switch { - FileStatus.Uploaded => "uploaded", - FileStatus.Processed => "processed", - FileStatus.Error => "error", + Files.FileStatus.Uploaded => "uploaded", + Files.FileStatus.Processed => "processed", + Files.FileStatus.Error => "error", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FileStatus value.") }; - public static FileStatus ToFileStatus(this string value) + public static Files.FileStatus ToFileStatus(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "uploaded")) return FileStatus.Uploaded; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "processed")) return FileStatus.Processed; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "error")) return FileStatus.Error; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "uploaded")) + { + return Files.FileStatus.Uploaded; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "processed")) + { + return Files.FileStatus.Processed; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "error")) + { + return Files.FileStatus.Error; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FileStatus value."); } } diff --git a/src/Generated/Models/FileUploadPurpose.cs b/src/Generated/Models/FileUploadPurpose.cs index 9c08633af..af423aa35 100644 --- a/src/Generated/Models/FileUploadPurpose.cs +++ b/src/Generated/Models/FileUploadPurpose.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { public readonly partial struct FileUploadPurpose : IEquatable { private readonly string _value; - - public FileUploadPurpose(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string AssistantsValue = "assistants"; private const string BatchValue = "batch"; private const string FineTuneValue = "fine-tune"; private const string VisionValue = "vision"; + public FileUploadPurpose(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static FileUploadPurpose Assistants { get; } = new FileUploadPurpose(AssistantsValue); + public static FileUploadPurpose Batch { get; } = new FileUploadPurpose(BatchValue); + public static FileUploadPurpose FineTune { get; } = new FileUploadPurpose(FineTuneValue); + public static FileUploadPurpose Vision { get; } = new FileUploadPurpose(VisionValue); + public static bool operator ==(FileUploadPurpose left, FileUploadPurpose right) => left.Equals(right); + public static bool operator !=(FileUploadPurpose left, FileUploadPurpose right) => !left.Equals(right); + public static implicit operator FileUploadPurpose(string value) => new FileUploadPurpose(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FileUploadPurpose other && Equals(other); + public bool Equals(FileUploadPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FineTuningIntegration.Serialization.cs b/src/Generated/Models/FineTuningIntegration.Serialization.cs index c2f16095d..f70dc849d 100644 --- a/src/Generated/Models/FineTuningIntegration.Serialization.cs +++ b/src/Generated/Models/FineTuningIntegration.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { [PersistableModelProxy(typeof(UnknownCreateFineTuningJobRequestIntegration))] - internal partial class FineTuningIntegration : IJsonModel + internal abstract partial class FineTuningIntegration : IJsonModel { + internal FineTuningIntegration() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningIntegration)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,43 +55,43 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - FineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningIntegration)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningIntegration(document.RootElement, options); } - internal static FineTuningIntegration DeserializeFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningIntegration DeserializeFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "wandb": return WeightsAndBiasesIntegration.DeserializeWeightsAndBiasesIntegration(element, options); + case "wandb": + return WeightsAndBiasesIntegration.DeserializeWeightsAndBiasesIntegration(element, options); } } return UnknownCreateFineTuningJobRequestIntegration.DeserializeUnknownCreateFineTuningJobRequestIntegration(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -91,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - FineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningIntegration(document.RootElement, options); } default: @@ -109,15 +120,20 @@ FineTuningIntegration IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningIntegration FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningIntegration fineTuningIntegration) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningIntegration(document.RootElement); + if (fineTuningIntegration == null) + { + return null; + } + return BinaryContent.Create(fineTuningIntegration, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningIntegration(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningIntegration(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningIntegration.cs b/src/Generated/Models/FineTuningIntegration.cs index 53daa38c0..9eccef658 100644 --- a/src/Generated/Models/FineTuningIntegration.cs +++ b/src/Generated/Models/FineTuningIntegration.cs @@ -9,17 +9,25 @@ namespace OpenAI.FineTuning { internal abstract partial class FineTuningIntegration { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected FineTuningIntegration() + private protected IDictionary _additionalBinaryDataProperties; + + private protected FineTuningIntegration(string @type) { + Type = @type; } - internal FineTuningIntegration(string type, IDictionary serializedAdditionalRawData) + internal FineTuningIntegration(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FineTuningIntegrationWandbWandb.Serialization.cs b/src/Generated/Models/FineTuningIntegrationWandbWandb.Serialization.cs index dea000f02..1001f4ab3 100644 --- a/src/Generated/Models/FineTuningIntegrationWandbWandb.Serialization.cs +++ b/src/Generated/Models/FineTuningIntegrationWandbWandb.Serialization.cs @@ -7,26 +7,36 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningIntegrationWandbWandb : IJsonModel { + internal FineTuningIntegrationWandbWandb() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningIntegrationWandbWandb)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("project") != true) + if (_additionalBinaryDataProperties?.ContainsKey("project") != true) { writer.WritePropertyName("project"u8); writer.WriteStringValue(Project); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -35,10 +45,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("entity") != true && Optional.IsDefined(Entity)) + if (Optional.IsDefined(Entity) && _additionalBinaryDataProperties?.ContainsKey("entity") != true) { if (Entity != null) { @@ -47,22 +57,27 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("entity"); + writer.WriteNull("entity"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tags") != true && Optional.IsCollectionDefined(Tags)) + if (Optional.IsCollectionDefined(Tags) && _additionalBinaryDataProperties?.ContainsKey("tags") != true) { writer.WritePropertyName("tags"u8); writer.WriteStartArray(); - foreach (var item in Tags) + foreach (string item in Tags) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -70,7 +85,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -79,25 +94,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - FineTuningIntegrationWandbWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningIntegrationWandbWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningIntegrationWandbWandb JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningIntegrationWandbWandb)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningIntegrationWandbWandb(document.RootElement, options); } - internal static FineTuningIntegrationWandbWandb DeserializeFineTuningIntegrationWandbWandb(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningIntegrationWandbWandb DeserializeFineTuningIntegrationWandbWandb(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -105,64 +118,69 @@ internal static FineTuningIntegrationWandbWandb DeserializeFineTuningIntegration string project = default; string name = default; string entity = default; - IReadOnlyList tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList tags = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("project"u8)) + if (prop.NameEquals("project"u8)) { - project = property.Value.GetString(); + project = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("entity"u8)) + if (prop.NameEquals("entity"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { entity = null; continue; } - entity = property.Value.GetString(); + entity = prop.Value.GetString(); continue; } - if (property.NameEquals("tags"u8)) + if (prop.NameEquals("tags"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } tags = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FineTuningIntegrationWandbWandb(project, name, entity, tags ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new FineTuningIntegrationWandbWandb(project, name, entity, tags ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -172,15 +190,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - FineTuningIntegrationWandbWandb IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningIntegrationWandbWandb IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningIntegrationWandbWandb 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningIntegrationWandbWandb(document.RootElement, options); } default: @@ -190,15 +209,20 @@ FineTuningIntegrationWandbWandb IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningIntegrationWandbWandb FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningIntegrationWandbWandb fineTuningIntegrationWandbWandb) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningIntegrationWandbWandb(document.RootElement); + if (fineTuningIntegrationWandbWandb == null) + { + return null; + } + return BinaryContent.Create(fineTuningIntegrationWandbWandb, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningIntegrationWandbWandb(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningIntegrationWandbWandb(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningIntegrationWandbWandb.cs b/src/Generated/Models/FineTuningIntegrationWandbWandb.cs index 6be0538b4..8d6a4b8fd 100644 --- a/src/Generated/Models/FineTuningIntegrationWandbWandb.cs +++ b/src/Generated/Models/FineTuningIntegrationWandbWandb.cs @@ -4,36 +4,41 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningIntegrationWandbWandb { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal FineTuningIntegrationWandbWandb(string project) { - Argument.AssertNotNull(project, nameof(project)); - Project = project; Tags = new ChangeTrackingList(); } - internal FineTuningIntegrationWandbWandb(string project, string name, string entity, IReadOnlyList tags, IDictionary serializedAdditionalRawData) + internal FineTuningIntegrationWandbWandb(string project, string name, string entity, IList tags, IDictionary additionalBinaryDataProperties) { Project = project; Name = name; Entity = entity; Tags = tags; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal FineTuningIntegrationWandbWandb() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Project { get; } + public string Name { get; } + public string Entity { get; } - public IReadOnlyList Tags { get; } + + public IList Tags { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FineTuningJob.Serialization.cs b/src/Generated/Models/FineTuningJob.Serialization.cs index 4a6339768..68aff9421 100644 --- a/src/Generated/Models/FineTuningJob.Serialization.cs +++ b/src/Generated/Models/FineTuningJob.Serialization.cs @@ -7,21 +7,31 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningJob : IJsonModel { + internal FineTuningJob() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningJob)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("user_provided_suffix") != true && Optional.IsDefined(UserProvidedSuffix)) + if (Optional.IsDefined(UserProvidedSuffix) && _additionalBinaryDataProperties?.ContainsKey("user_provided_suffix") != true) { if (UserProvidedSuffix != null) { @@ -30,20 +40,20 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("user_provided_suffix"); + writer.WriteNull("userProvidedSuffix"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("error") != true) { if (Error != null) { @@ -52,10 +62,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("error"); + writer.WriteNull("error"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("fine_tuned_model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("fine_tuned_model") != true) { if (FineTunedModel != null) { @@ -64,10 +74,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("fine_tuned_model"); + writer.WriteNull("fineTunedModel"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("finished_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("finished_at") != true) { if (FinishedAt != null) { @@ -76,45 +86,50 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("finished_at"); + writer.WriteNull("finishedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("hyperparameters") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hyperparameters") != true) { writer.WritePropertyName("hyperparameters"u8); writer.WriteObjectValue(Hyperparameters, options); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("organization_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("organization_id") != true) { writer.WritePropertyName("organization_id"u8); writer.WriteStringValue(OrganizationId); } - if (SerializedAdditionalRawData?.ContainsKey("result_files") != true) + if (_additionalBinaryDataProperties?.ContainsKey("result_files") != true) { writer.WritePropertyName("result_files"u8); writer.WriteStartArray(); - foreach (var item in ResultFiles) + foreach (string item in ResultFiles) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("trained_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("trained_tokens") != true) { if (TrainedTokens != null) { @@ -123,15 +138,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("trained_tokens"); + writer.WriteNull("trainedTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("training_file") != true) + if (_additionalBinaryDataProperties?.ContainsKey("training_file") != true) { writer.WritePropertyName("training_file"u8); writer.WriteStringValue(TrainingFile); } - if (SerializedAdditionalRawData?.ContainsKey("validation_file") != true) + if (_additionalBinaryDataProperties?.ContainsKey("validation_file") != true) { if (ValidationFile != null) { @@ -140,16 +155,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("validation_file"); + writer.WriteNull("validationFile"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("integrations") != true && Optional.IsCollectionDefined(Integrations)) + if (Optional.IsCollectionDefined(Integrations) && _additionalBinaryDataProperties?.ContainsKey("integrations") != true) { if (Integrations != null) { writer.WritePropertyName("integrations"u8); writer.WriteStartArray(); - foreach (var item in Integrations) + foreach (InternalFineTuningIntegration item in Integrations) { writer.WriteObjectValue(item, options); } @@ -157,15 +172,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("integrations"); + writer.WriteNull("integrations"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("seed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("seed") != true) { writer.WritePropertyName("seed"u8); writer.WriteNumberValue(Seed); } - if (SerializedAdditionalRawData?.ContainsKey("estimated_finish") != true && Optional.IsDefined(EstimatedFinish)) + if (Optional.IsDefined(EstimatedFinish) && _additionalBinaryDataProperties?.ContainsKey("estimated_finish") != true) { if (EstimatedFinish != null) { @@ -174,12 +189,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("estimated_finish"); + writer.WriteNull("estimatedFinish"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -187,7 +202,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -196,25 +211,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt #endif } } - writer.WriteEndObject(); } - FineTuningJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningJob JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningJob)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningJob(document.RootElement, options); } - internal static FineTuningJob DeserializeFineTuningJob(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningJob DeserializeFineTuningJob(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -229,164 +242,168 @@ internal static FineTuningJob DeserializeFineTuningJob(JsonElement element, Mode string model = default; InternalFineTuningJobObject @object = default; string organizationId = default; - IReadOnlyList resultFiles = default; + IList resultFiles = default; FineTuningJobStatus status = default; int? trainedTokens = default; string trainingFile = default; string validationFile = default; - IReadOnlyList integrations = default; + IList integrations = default; int seed = default; DateTimeOffset? estimatedFinish = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("user_provided_suffix"u8)) + if (prop.NameEquals("user_provided_suffix"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { userProvidedSuffix = null; continue; } - userProvidedSuffix = property.Value.GetString(); + userProvidedSuffix = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("error"u8)) + if (prop.NameEquals("error"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { error = null; continue; } - error = FineTuningJobError.DeserializeFineTuningJobError(property.Value, options); + error = FineTuningJobError.DeserializeFineTuningJobError(prop.Value, options); continue; } - if (property.NameEquals("fine_tuned_model"u8)) + if (prop.NameEquals("fine_tuned_model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { fineTunedModel = null; continue; } - fineTunedModel = property.Value.GetString(); + fineTunedModel = prop.Value.GetString(); continue; } - if (property.NameEquals("finished_at"u8)) + if (prop.NameEquals("finished_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { finishedAt = null; continue; } - finishedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + finishedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("hyperparameters"u8)) + if (prop.NameEquals("hyperparameters"u8)) { - hyperparameters = FineTuningJobHyperparameters.DeserializeFineTuningJobHyperparameters(property.Value, options); + hyperparameters = FineTuningJobHyperparameters.DeserializeFineTuningJobHyperparameters(prop.Value, options); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalFineTuningJobObject(property.Value.GetString()); + @object = new InternalFineTuningJobObject(prop.Value.GetString()); continue; } - if (property.NameEquals("organization_id"u8)) + if (prop.NameEquals("organization_id"u8)) { - organizationId = property.Value.GetString(); + organizationId = prop.Value.GetString(); continue; } - if (property.NameEquals("result_files"u8)) + if (prop.NameEquals("result_files"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } resultFiles = array; continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new FineTuningJobStatus(property.Value.GetString()); + status = new FineTuningJobStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("trained_tokens"u8)) + if (prop.NameEquals("trained_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { trainedTokens = null; continue; } - trainedTokens = property.Value.GetInt32(); + trainedTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("training_file"u8)) + if (prop.NameEquals("training_file"u8)) { - trainingFile = property.Value.GetString(); + trainingFile = prop.Value.GetString(); continue; } - if (property.NameEquals("validation_file"u8)) + if (prop.NameEquals("validation_file"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { validationFile = null; continue; } - validationFile = property.Value.GetString(); + validationFile = prop.Value.GetString(); continue; } - if (property.NameEquals("integrations"u8)) + if (prop.NameEquals("integrations"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalFineTuningIntegration.DeserializeInternalFineTuningIntegration(item, options)); } integrations = array; continue; } - if (property.NameEquals("seed"u8)) + if (prop.NameEquals("seed"u8)) { - seed = property.Value.GetInt32(); + seed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("estimated_finish"u8)) + if (prop.NameEquals("estimated_finish"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { estimatedFinish = null; continue; } - estimatedFinish = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + estimatedFinish = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new FineTuningJob( userProvidedSuffix, id, @@ -406,13 +423,14 @@ internal static FineTuningJob DeserializeFineTuningJob(JsonElement element, Mode integrations ?? new ChangeTrackingList(), seed, estimatedFinish, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -422,15 +440,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions optio } } - FineTuningJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningJob 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningJob(document.RootElement, options); } default: @@ -440,15 +459,20 @@ FineTuningJob IPersistableModel.Create(BinaryData data, ModelRead string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningJob FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningJob fineTuningJob) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningJob(document.RootElement); + if (fineTuningJob == null) + { + return null; + } + return BinaryContent.Create(fineTuningJob, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningJob(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningJob(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningJob.cs b/src/Generated/Models/FineTuningJob.cs index fc955ef7f..cd8649531 100644 --- a/src/Generated/Models/FineTuningJob.cs +++ b/src/Generated/Models/FineTuningJob.cs @@ -5,20 +5,16 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningJob { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal FineTuningJob(string id, DateTimeOffset createdAt, FineTuningJobError error, string fineTunedModel, DateTimeOffset? finishedAt, FineTuningJobHyperparameters hyperparameters, string model, string organizationId, IEnumerable resultFiles, FineTuningJobStatus status, int? trainedTokens, string trainingFile, string validationFile, int seed) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(model, nameof(model)); - Argument.AssertNotNull(organizationId, nameof(organizationId)); - Argument.AssertNotNull(resultFiles, nameof(resultFiles)); - Argument.AssertNotNull(trainingFile, nameof(trainingFile)); - Id = id; CreatedAt = createdAt; Error = error; @@ -36,7 +32,7 @@ internal FineTuningJob(string id, DateTimeOffset createdAt, FineTuningJobError e Seed = seed; } - internal FineTuningJob(string userProvidedSuffix, string id, DateTimeOffset createdAt, FineTuningJobError error, string fineTunedModel, DateTimeOffset? finishedAt, FineTuningJobHyperparameters hyperparameters, string model, InternalFineTuningJobObject @object, string organizationId, IReadOnlyList resultFiles, FineTuningJobStatus status, int? trainedTokens, string trainingFile, string validationFile, IReadOnlyList integrations, int seed, DateTimeOffset? estimatedFinish, IDictionary serializedAdditionalRawData) + internal FineTuningJob(string userProvidedSuffix, string id, DateTimeOffset createdAt, FineTuningJobError error, string fineTunedModel, DateTimeOffset? finishedAt, FineTuningJobHyperparameters hyperparameters, string model, InternalFineTuningJobObject @object, string organizationId, IList resultFiles, FineTuningJobStatus status, int? trainedTokens, string trainingFile, string validationFile, IList integrations, int seed, DateTimeOffset? estimatedFinish, IDictionary additionalBinaryDataProperties) { UserProvidedSuffix = userProvidedSuffix; Id = id; @@ -56,31 +52,49 @@ internal FineTuningJob(string userProvidedSuffix, string id, DateTimeOffset crea Integrations = integrations; Seed = seed; EstimatedFinish = estimatedFinish; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal FineTuningJob() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string UserProvidedSuffix { get; } + public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public FineTuningJobError Error { get; } + public string FineTunedModel { get; } + public DateTimeOffset? FinishedAt { get; } + public FineTuningJobHyperparameters Hyperparameters { get; } + public string Model { get; } - public InternalFineTuningJobObject Object { get; } = InternalFineTuningJobObject.FineTuningJob; + + public InternalFineTuningJobObject Object { get; } = "fine_tuning.job"; public string OrganizationId { get; } - public IReadOnlyList ResultFiles { get; } + + public IList ResultFiles { get; } + public FineTuningJobStatus Status { get; } + public int? TrainedTokens { get; } + public string TrainingFile { get; } + public string ValidationFile { get; } - public IReadOnlyList Integrations { get; } + + public IList Integrations { get; } + public int Seed { get; } + public DateTimeOffset? EstimatedFinish { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FineTuningJobError.Serialization.cs b/src/Generated/Models/FineTuningJobError.Serialization.cs index 67b618563..20bbc87e6 100644 --- a/src/Generated/Models/FineTuningJobError.Serialization.cs +++ b/src/Generated/Models/FineTuningJobError.Serialization.cs @@ -7,31 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningJobError : IJsonModel { + internal FineTuningJobError() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningJobError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) + if (_additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("param") != true) + if (_additionalBinaryDataProperties?.ContainsKey("param") != true) { if (Param != null) { @@ -40,12 +50,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("param"); + writer.WriteNull("param"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,70 +72,66 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - FineTuningJobError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningJobError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningJobError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningJobError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningJobError(document.RootElement, options); } - internal static FineTuningJobError DeserializeFineTuningJobError(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningJobError DeserializeFineTuningJobError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string code = default; string message = default; - string param = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @param = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("param"u8)) + if (prop.NameEquals("param"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - param = null; + @param = null; continue; } - param = property.Value.GetString(); + @param = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FineTuningJobError(code, message, param, serializedAdditionalRawData); + return new FineTuningJobError(code, message, @param, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +141,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - FineTuningJobError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningJobError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningJobError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningJobError(document.RootElement, options); } default: @@ -153,15 +160,20 @@ FineTuningJobError IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningJobError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningJobError fineTuningJobError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningJobError(document.RootElement); + if (fineTuningJobError == null) + { + return null; + } + return BinaryContent.Create(fineTuningJobError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningJobError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningJobError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningJobError.cs b/src/Generated/Models/FineTuningJobError.cs index dbd6f4103..b31e40458 100644 --- a/src/Generated/Models/FineTuningJobError.cs +++ b/src/Generated/Models/FineTuningJobError.cs @@ -9,31 +9,33 @@ namespace OpenAI.FineTuning { internal partial class FineTuningJobError { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal FineTuningJobError(string code, string message, string param) - { - Argument.AssertNotNull(code, nameof(code)); - Argument.AssertNotNull(message, nameof(message)); + private protected IDictionary _additionalBinaryDataProperties; + internal FineTuningJobError(string code, string message, string @param) + { Code = code; Message = message; - Param = param; + Param = @param; } - internal FineTuningJobError(string code, string message, string param, IDictionary serializedAdditionalRawData) + internal FineTuningJobError(string code, string message, string @param, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - Param = param; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal FineTuningJobError() - { + Param = @param; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Code { get; } + public string Message { get; } + public string Param { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FineTuningJobEvent.Serialization.cs b/src/Generated/Models/FineTuningJobEvent.Serialization.cs index d03b6f085..2c3beecb5 100644 --- a/src/Generated/Models/FineTuningJobEvent.Serialization.cs +++ b/src/Generated/Models/FineTuningJobEvent.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningJobEvent : IJsonModel { + internal FineTuningJobEvent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningJobEvent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("level") != true) + if (_additionalBinaryDataProperties?.ContainsKey("level") != true) { writer.WritePropertyName("level"u8); writer.WriteStringValue(Level.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,83 +75,79 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - FineTuningJobEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningJobEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningJobEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningJobEvent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningJobEvent(document.RootElement, options); } - internal static FineTuningJobEvent DeserializeFineTuningJobEvent(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningJobEvent DeserializeFineTuningJobEvent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; DateTimeOffset createdAt = default; - FineTuningJobEventLevel level = default; + FineTuning.FineTuningJobEventLevel level = default; string message = default; InternalFineTuningJobEventObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("level"u8)) + if (prop.NameEquals("level"u8)) { - level = property.Value.GetString().ToFineTuningJobEventLevel(); + level = prop.Value.GetString().ToFineTuningJobEventLevel(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalFineTuningJobEventObject(property.Value.GetString()); + @object = new InternalFineTuningJobEventObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new FineTuningJobEvent( id, createdAt, level, message, @object, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +157,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - FineTuningJobEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningJobEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningJobEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningJobEvent(document.RootElement, options); } default: @@ -169,15 +176,20 @@ FineTuningJobEvent IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningJobEvent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningJobEvent fineTuningJobEvent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningJobEvent(document.RootElement); + if (fineTuningJobEvent == null) + { + return null; + } + return BinaryContent.Create(fineTuningJobEvent, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningJobEvent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningJobEvent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningJobEvent.cs b/src/Generated/Models/FineTuningJobEvent.cs index 5b169027b..223fb4005 100644 --- a/src/Generated/Models/FineTuningJobEvent.cs +++ b/src/Generated/Models/FineTuningJobEvent.cs @@ -9,36 +9,40 @@ namespace OpenAI.FineTuning { internal partial class FineTuningJobEvent { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal FineTuningJobEvent(string id, DateTimeOffset createdAt, FineTuningJobEventLevel level, string message) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(message, nameof(message)); + private protected IDictionary _additionalBinaryDataProperties; + internal FineTuningJobEvent(string id, DateTimeOffset createdAt, FineTuning.FineTuningJobEventLevel level, string message) + { Id = id; CreatedAt = createdAt; Level = level; Message = message; } - internal FineTuningJobEvent(string id, DateTimeOffset createdAt, FineTuningJobEventLevel level, string message, InternalFineTuningJobEventObject @object, IDictionary serializedAdditionalRawData) + internal FineTuningJobEvent(string id, DateTimeOffset createdAt, FineTuning.FineTuningJobEventLevel level, string message, InternalFineTuningJobEventObject @object, IDictionary additionalBinaryDataProperties) { Id = id; CreatedAt = createdAt; Level = level; Message = message; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal FineTuningJobEvent() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public DateTimeOffset CreatedAt { get; } - public FineTuningJobEventLevel Level { get; } + + public FineTuning.FineTuningJobEventLevel Level { get; } + public string Message { get; } - public InternalFineTuningJobEventObject Object { get; } = InternalFineTuningJobEventObject.FineTuningJobEvent; + + public InternalFineTuningJobEventObject Object { get; } = "fine_tuning.job.event"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FineTuningJobEventLevel.Serialization.cs b/src/Generated/Models/FineTuningJobEventLevel.Serialization.cs index e827bcb6d..18ef3bc2a 100644 --- a/src/Generated/Models/FineTuningJobEventLevel.Serialization.cs +++ b/src/Generated/Models/FineTuningJobEventLevel.Serialization.cs @@ -8,19 +8,28 @@ namespace OpenAI.FineTuning { internal static partial class FineTuningJobEventLevelExtensions { - public static string ToSerialString(this FineTuningJobEventLevel value) => value switch + public static string ToSerialString(this FineTuning.FineTuningJobEventLevel value) => value switch { - FineTuningJobEventLevel.Info => "info", - FineTuningJobEventLevel.Warn => "warn", - FineTuningJobEventLevel.Error => "error", + FineTuning.FineTuningJobEventLevel.Info => "info", + FineTuning.FineTuningJobEventLevel.Warn => "warn", + FineTuning.FineTuningJobEventLevel.Error => "error", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FineTuningJobEventLevel value.") }; - public static FineTuningJobEventLevel ToFineTuningJobEventLevel(this string value) + public static FineTuning.FineTuningJobEventLevel ToFineTuningJobEventLevel(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "info")) return FineTuningJobEventLevel.Info; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "warn")) return FineTuningJobEventLevel.Warn; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "error")) return FineTuningJobEventLevel.Error; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "info")) + { + return FineTuning.FineTuningJobEventLevel.Info; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "warn")) + { + return FineTuning.FineTuningJobEventLevel.Warn; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "error")) + { + return FineTuning.FineTuningJobEventLevel.Error; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown FineTuningJobEventLevel value."); } } diff --git a/src/Generated/Models/FineTuningJobHyperparameters.Serialization.cs b/src/Generated/Models/FineTuningJobHyperparameters.Serialization.cs index b264c7309..abe7ba36f 100644 --- a/src/Generated/Models/FineTuningJobHyperparameters.Serialization.cs +++ b/src/Generated/Models/FineTuningJobHyperparameters.Serialization.cs @@ -7,25 +7,35 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { - internal partial struct FineTuningJobHyperparameters : IJsonModel, IJsonModel + internal readonly partial struct FineTuningJobHyperparameters : IJsonModel, IJsonModel { + public FineTuningJobHyperparameters() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + private 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(FineTuningJobHyperparameters)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("n_epochs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("n_epochs") != true) { writer.WritePropertyName("n_epochs"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(NEpochs); + writer.WriteRawValue(NEpochs); #else using (JsonDocument document = JsonDocument.Parse(NEpochs)) { @@ -33,11 +43,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } #endif } - if (SerializedAdditionalRawData?.ContainsKey("batch_size") != true) + if (_additionalBinaryDataProperties?.ContainsKey("batch_size") != true) { writer.WritePropertyName("batch_size"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(BatchSize); + writer.WriteRawValue(BatchSize); #else using (JsonDocument document = JsonDocument.Parse(BatchSize)) { @@ -45,11 +55,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } #endif } - if (SerializedAdditionalRawData?.ContainsKey("learning_rate_multiplier") != true) + if (_additionalBinaryDataProperties?.ContainsKey("learning_rate_multiplier") != true) { writer.WritePropertyName("learning_rate_multiplier"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(LearningRateMultiplier); + writer.WriteRawValue(LearningRateMultiplier); #else using (JsonDocument document = JsonDocument.Parse(LearningRateMultiplier)) { @@ -57,9 +67,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -67,7 +77,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -76,65 +86,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - FineTuningJobHyperparameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningJobHyperparameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + private FineTuningJobHyperparameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningJobHyperparameters)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningJobHyperparameters(document.RootElement, options); } - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); - - object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); - - internal static FineTuningJobHyperparameters DeserializeFineTuningJobHyperparameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningJobHyperparameters DeserializeFineTuningJobHyperparameters(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - + if (element.ValueKind == JsonValueKind.Null) + { + return default; + } BinaryData nEpochs = default; BinaryData batchSize = default; BinaryData learningRateMultiplier = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("n_epochs"u8)) + if (prop.NameEquals("n_epochs"u8)) { - nEpochs = BinaryData.FromString(property.Value.GetRawText()); + nEpochs = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("batch_size"u8)) + if (prop.NameEquals("batch_size"u8)) { - batchSize = BinaryData.FromString(property.Value.GetRawText()); + batchSize = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("learning_rate_multiplier"u8)) + if (prop.NameEquals("learning_rate_multiplier"u8)) { - learningRateMultiplier = BinaryData.FromString(property.Value.GetRawText()); + learningRateMultiplier = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FineTuningJobHyperparameters(nEpochs, batchSize, learningRateMultiplier, serializedAdditionalRawData); + return new FineTuningJobHyperparameters(nEpochs, batchSize, learningRateMultiplier, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + private BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -144,15 +150,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - FineTuningJobHyperparameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningJobHyperparameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + private FineTuningJobHyperparameters 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningJobHyperparameters(document.RootElement, options); } default: @@ -162,21 +169,26 @@ FineTuningJobHyperparameters IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); - - object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); - - internal static FineTuningJobHyperparameters FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningJobHyperparameters fineTuningJobHyperparameters) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningJobHyperparameters(document.RootElement); + return BinaryContent.Create(fineTuningJobHyperparameters, ModelSerializationExtensions.WireOptions); } - internal BinaryContent ToBinaryContent() + public static explicit operator FineTuningJobHyperparameters(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningJobHyperparameters(document.RootElement, ModelSerializationExtensions.WireOptions); } + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); + + object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); + + object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); } } diff --git a/src/Generated/Models/FineTuningJobHyperparameters.cs b/src/Generated/Models/FineTuningJobHyperparameters.cs index 747e99476..2da0a095b 100644 --- a/src/Generated/Models/FineTuningJobHyperparameters.cs +++ b/src/Generated/Models/FineTuningJobHyperparameters.cs @@ -9,27 +9,23 @@ namespace OpenAI.FineTuning { internal readonly partial struct FineTuningJobHyperparameters { + private readonly IDictionary _additionalBinaryDataProperties; + internal FineTuningJobHyperparameters(BinaryData nEpochs, BinaryData batchSize, BinaryData learningRateMultiplier) { - Argument.AssertNotNull(nEpochs, nameof(nEpochs)); - Argument.AssertNotNull(batchSize, nameof(batchSize)); - Argument.AssertNotNull(learningRateMultiplier, nameof(learningRateMultiplier)); - NEpochs = nEpochs; BatchSize = batchSize; LearningRateMultiplier = learningRateMultiplier; } - internal FineTuningJobHyperparameters(BinaryData nEpochs, BinaryData batchSize, BinaryData learningRateMultiplier, IDictionary serializedAdditionalRawData) + internal FineTuningJobHyperparameters(BinaryData nEpochs, BinaryData batchSize, BinaryData learningRateMultiplier, IDictionary additionalBinaryDataProperties) { NEpochs = nEpochs; BatchSize = batchSize; LearningRateMultiplier = learningRateMultiplier; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public FineTuningJobHyperparameters() - { - } + internal IDictionary SerializedAdditionalRawData => _additionalBinaryDataProperties; } } diff --git a/src/Generated/Models/FineTuningJobHyperparametersBatchSizeChoiceEnum.cs b/src/Generated/Models/FineTuningJobHyperparametersBatchSizeChoiceEnum.cs index 1349f4677..e5ad18b8d 100644 --- a/src/Generated/Models/FineTuningJobHyperparametersBatchSizeChoiceEnum.cs +++ b/src/Generated/Models/FineTuningJobHyperparametersBatchSizeChoiceEnum.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct FineTuningJobHyperparametersBatchSizeChoiceEnum : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public FineTuningJobHyperparametersBatchSizeChoiceEnum(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static FineTuningJobHyperparametersBatchSizeChoiceEnum Auto { get; } = new FineTuningJobHyperparametersBatchSizeChoiceEnum(AutoValue); + public static bool operator ==(FineTuningJobHyperparametersBatchSizeChoiceEnum left, FineTuningJobHyperparametersBatchSizeChoiceEnum right) => left.Equals(right); + public static bool operator !=(FineTuningJobHyperparametersBatchSizeChoiceEnum left, FineTuningJobHyperparametersBatchSizeChoiceEnum right) => !left.Equals(right); + public static implicit operator FineTuningJobHyperparametersBatchSizeChoiceEnum(string value) => new FineTuningJobHyperparametersBatchSizeChoiceEnum(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FineTuningJobHyperparametersBatchSizeChoiceEnum other && Equals(other); + public bool Equals(FineTuningJobHyperparametersBatchSizeChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum.cs b/src/Generated/Models/FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum.cs index 7aa3f46ca..87c2d5e3c 100644 --- a/src/Generated/Models/FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum.cs +++ b/src/Generated/Models/FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum Auto { get; } = new FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum(AutoValue); + public static bool operator ==(FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum left, FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum right) => left.Equals(right); + public static bool operator !=(FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum left, FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum right) => !left.Equals(right); + public static implicit operator FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum(string value) => new FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum other && Equals(other); + public bool Equals(FineTuningJobHyperparametersLearningRateMultiplierChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FineTuningJobHyperparametersNEpochsChoiceEnum.cs b/src/Generated/Models/FineTuningJobHyperparametersNEpochsChoiceEnum.cs index 7ba8e753d..f4b40d5f3 100644 --- a/src/Generated/Models/FineTuningJobHyperparametersNEpochsChoiceEnum.cs +++ b/src/Generated/Models/FineTuningJobHyperparametersNEpochsChoiceEnum.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct FineTuningJobHyperparametersNEpochsChoiceEnum : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public FineTuningJobHyperparametersNEpochsChoiceEnum(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static FineTuningJobHyperparametersNEpochsChoiceEnum Auto { get; } = new FineTuningJobHyperparametersNEpochsChoiceEnum(AutoValue); + public static bool operator ==(FineTuningJobHyperparametersNEpochsChoiceEnum left, FineTuningJobHyperparametersNEpochsChoiceEnum right) => left.Equals(right); + public static bool operator !=(FineTuningJobHyperparametersNEpochsChoiceEnum left, FineTuningJobHyperparametersNEpochsChoiceEnum right) => !left.Equals(right); + public static implicit operator FineTuningJobHyperparametersNEpochsChoiceEnum(string value) => new FineTuningJobHyperparametersNEpochsChoiceEnum(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FineTuningJobHyperparametersNEpochsChoiceEnum other && Equals(other); + public bool Equals(FineTuningJobHyperparametersNEpochsChoiceEnum other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FineTuningJobStatus.cs b/src/Generated/Models/FineTuningJobStatus.cs index 0c9e12360..babe3cece 100644 --- a/src/Generated/Models/FineTuningJobStatus.cs +++ b/src/Generated/Models/FineTuningJobStatus.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct FineTuningJobStatus : IEquatable { private readonly string _value; - - public FineTuningJobStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string ValidatingFilesValue = "validating_files"; private const string QueuedValue = "queued"; private const string RunningValue = "running"; @@ -23,22 +18,39 @@ public FineTuningJobStatus(string value) private const string FailedValue = "failed"; private const string CancelledValue = "cancelled"; + public FineTuningJobStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static FineTuningJobStatus ValidatingFiles { get; } = new FineTuningJobStatus(ValidatingFilesValue); + public static FineTuningJobStatus Queued { get; } = new FineTuningJobStatus(QueuedValue); + public static FineTuningJobStatus Running { get; } = new FineTuningJobStatus(RunningValue); + public static FineTuningJobStatus Succeeded { get; } = new FineTuningJobStatus(SucceededValue); + public static FineTuningJobStatus Failed { get; } = new FineTuningJobStatus(FailedValue); + public static FineTuningJobStatus Cancelled { get; } = new FineTuningJobStatus(CancelledValue); + public static bool operator ==(FineTuningJobStatus left, FineTuningJobStatus right) => left.Equals(right); + public static bool operator !=(FineTuningJobStatus left, FineTuningJobStatus right) => !left.Equals(right); + public static implicit operator FineTuningJobStatus(string value) => new FineTuningJobStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is FineTuningJobStatus other && Equals(other); + public bool Equals(FineTuningJobStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/FineTuningOptions.Serialization.cs b/src/Generated/Models/FineTuningOptions.Serialization.cs index 76726dc27..eeaf45f5e 100644 --- a/src/Generated/Models/FineTuningOptions.Serialization.cs +++ b/src/Generated/Models/FineTuningOptions.Serialization.cs @@ -7,36 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningOptions : IJsonModel { + internal FineTuningOptions() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("training_file") != true) + if (_additionalBinaryDataProperties?.ContainsKey("training_file") != true) { writer.WritePropertyName("training_file"u8); writer.WriteStringValue(TrainingFile); } - if (SerializedAdditionalRawData?.ContainsKey("hyperparameters") != true && Optional.IsDefined(Hyperparameters)) + if (Optional.IsDefined(Hyperparameters) && _additionalBinaryDataProperties?.ContainsKey("hyperparameters") != true) { writer.WritePropertyName("hyperparameters"u8); writer.WriteObjectValue(Hyperparameters, options); } - if (SerializedAdditionalRawData?.ContainsKey("suffix") != true && Optional.IsDefined(Suffix)) + if (Optional.IsDefined(Suffix) && _additionalBinaryDataProperties?.ContainsKey("suffix") != true) { if (Suffix != null) { @@ -45,10 +55,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } else { - writer.WriteNull("suffix"); + writer.WriteNull("suffix"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("validation_file") != true && Optional.IsDefined(ValidationFile)) + if (Optional.IsDefined(ValidationFile) && _additionalBinaryDataProperties?.ContainsKey("validation_file") != true) { if (ValidationFile != null) { @@ -57,16 +67,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } else { - writer.WriteNull("validation_file"); + writer.WriteNull("validationFile"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("integrations") != true && Optional.IsCollectionDefined(Integrations)) + if (Optional.IsCollectionDefined(Integrations) && _additionalBinaryDataProperties?.ContainsKey("integrations") != true) { if (Integrations != null) { writer.WritePropertyName("integrations"u8); writer.WriteStartArray(); - foreach (var item in Integrations) + foreach (FineTuningIntegration item in Integrations) { writer.WriteObjectValue(item, options); } @@ -74,10 +84,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } else { - writer.WriteNull("integrations"); + writer.WriteNull("integrations"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("seed") != true && Optional.IsDefined(Seed)) + if (Optional.IsDefined(Seed) && _additionalBinaryDataProperties?.ContainsKey("seed") != true) { if (Seed != null) { @@ -86,12 +96,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } else { - writer.WriteNull("seed"); + writer.WriteNull("seed"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -99,7 +109,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -108,25 +118,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite #endif } } - writer.WriteEndObject(); } - FineTuningOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual FineTuningOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningOptions(document.RootElement, options); } - internal static FineTuningOptions DeserializeFineTuningOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static FineTuningOptions DeserializeFineTuningOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -138,80 +146,77 @@ internal static FineTuningOptions DeserializeFineTuningOptions(JsonElement eleme string validationFile = default; IList integrations = default; int? seed = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = new InternalCreateFineTuningJobRequestModel(property.Value.GetString()); + model = new InternalCreateFineTuningJobRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("training_file"u8)) + if (prop.NameEquals("training_file"u8)) { - trainingFile = property.Value.GetString(); + trainingFile = prop.Value.GetString(); continue; } - if (property.NameEquals("hyperparameters"u8)) + if (prop.NameEquals("hyperparameters"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - hyperparameters = HyperparameterOptions.DeserializeHyperparameterOptions(property.Value, options); + hyperparameters = HyperparameterOptions.DeserializeHyperparameterOptions(prop.Value, options); continue; } - if (property.NameEquals("suffix"u8)) + if (prop.NameEquals("suffix"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { suffix = null; continue; } - suffix = property.Value.GetString(); + suffix = prop.Value.GetString(); continue; } - if (property.NameEquals("validation_file"u8)) + if (prop.NameEquals("validation_file"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { validationFile = null; continue; } - validationFile = property.Value.GetString(); + validationFile = prop.Value.GetString(); continue; } - if (property.NameEquals("integrations"u8)) + if (prop.NameEquals("integrations"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(FineTuningIntegration.DeserializeFineTuningIntegration(item, options)); } integrations = array; continue; } - if (property.NameEquals("seed"u8)) + if (prop.NameEquals("seed"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { seed = null; continue; } - seed = property.Value.GetInt32(); + seed = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new FineTuningOptions( model, trainingFile, @@ -220,13 +225,14 @@ internal static FineTuningOptions DeserializeFineTuningOptions(JsonElement eleme validationFile, integrations ?? new ChangeTrackingList(), seed, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -236,15 +242,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions o } } - FineTuningOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual FineTuningOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningOptions(document.RootElement, options); } default: @@ -254,15 +261,20 @@ FineTuningOptions IPersistableModel.Create(BinaryData data, M string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static FineTuningOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FineTuningOptions fineTuningOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFineTuningOptions(document.RootElement); + if (fineTuningOptions == null) + { + return null; + } + return BinaryContent.Create(fineTuningOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator FineTuningOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFineTuningOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FineTuningOptions.cs b/src/Generated/Models/FineTuningOptions.cs index 0cbb53b8d..1fece15c9 100644 --- a/src/Generated/Models/FineTuningOptions.cs +++ b/src/Generated/Models/FineTuningOptions.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.FineTuning { internal partial class FineTuningOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public FineTuningOptions(InternalCreateFineTuningJobRequestModel model, string trainingFile) { Argument.AssertNotNull(trainingFile, nameof(trainingFile)); @@ -19,7 +21,7 @@ public FineTuningOptions(InternalCreateFineTuningJobRequestModel model, string t Integrations = new ChangeTrackingList(); } - internal FineTuningOptions(InternalCreateFineTuningJobRequestModel model, string trainingFile, HyperparameterOptions hyperparameters, string suffix, string validationFile, IList integrations, int? seed, IDictionary serializedAdditionalRawData) + internal FineTuningOptions(InternalCreateFineTuningJobRequestModel model, string trainingFile, HyperparameterOptions hyperparameters, string suffix, string validationFile, IList integrations, int? seed, IDictionary additionalBinaryDataProperties) { Model = model; TrainingFile = trainingFile; @@ -28,19 +30,27 @@ internal FineTuningOptions(InternalCreateFineTuningJobRequestModel model, string ValidationFile = validationFile; Integrations = integrations; Seed = seed; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal FineTuningOptions() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateFineTuningJobRequestModel Model { get; } + public string TrainingFile { get; } + public HyperparameterOptions Hyperparameters { get; set; } + public string Suffix { get; set; } + public string ValidationFile { get; set; } + public IList Integrations { get; set; } + public int? Seed { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/FunctionChatMessage.Serialization.cs b/src/Generated/Models/FunctionChatMessage.Serialization.cs index 5ce2dae5b..0c452e997 100644 --- a/src/Generated/Models/FunctionChatMessage.Serialization.cs +++ b/src/Generated/Models/FunctionChatMessage.Serialization.cs @@ -7,68 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class FunctionChatMessage : IJsonModel { - FunctionChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal FunctionChatMessage() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(FunctionChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FunctionChatMessage)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(FunctionName); } + } + + FunctionChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (FunctionChatMessage)JsonModelCreateCore(ref reader, options); + 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(FunctionChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFunctionChatMessage(document.RootElement, options); } - internal static FunctionChatMessage DeserializeFunctionChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static FunctionChatMessage DeserializeFunctionChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string name = default; - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string functionName = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("role"u8)) { - name = property.Value.GetString(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("content"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + DeserializeContentValue(prop, ref content); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("name"u8)) { - DeserializeContentValue(property, ref content); + functionName = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. - return new FunctionChatMessage(role, content ?? new ChatMessageContent(), serializedAdditionalRawData, name); + return new FunctionChatMessage(role, content ?? new ChatMessageContent(), additionalBinaryDataProperties, functionName); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -78,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - FunctionChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FunctionChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (FunctionChatMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFunctionChatMessage(document.RootElement, options); } default: @@ -96,15 +114,20 @@ FunctionChatMessage IPersistableModel.Create(BinaryData dat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new FunctionChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FunctionChatMessage functionChatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFunctionChatMessage(document.RootElement); + if (functionChatMessage == null) + { + return null; + } + return BinaryContent.Create(functionChatMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator FunctionChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFunctionChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FunctionChatMessage.cs b/src/Generated/Models/FunctionChatMessage.cs index bb9deef10..688e7abc6 100644 --- a/src/Generated/Models/FunctionChatMessage.cs +++ b/src/Generated/Models/FunctionChatMessage.cs @@ -9,13 +9,9 @@ namespace OpenAI.Chat { public partial class FunctionChatMessage : ChatMessage { - internal FunctionChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string functionName) : base(role, content, serializedAdditionalRawData) + internal FunctionChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string functionName) : base(role, content, additionalBinaryDataProperties) { FunctionName = functionName; } - - internal FunctionChatMessage() - { - } } } diff --git a/src/Generated/Models/FunctionToolDefinition.Serialization.cs b/src/Generated/Models/FunctionToolDefinition.Serialization.cs index e17ea82e9..fc2d3992f 100644 --- a/src/Generated/Models/FunctionToolDefinition.Serialization.cs +++ b/src/Generated/Models/FunctionToolDefinition.Serialization.cs @@ -7,61 +7,74 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class FunctionToolDefinition : IJsonModel { - FunctionToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(FunctionToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FunctionToolDefinition)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(_internalFunction, options); } + } + + FunctionToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (FunctionToolDefinition)JsonModelCreateCore(ref reader, options); + protected override ToolDefinition 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(FunctionToolDefinition)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFunctionToolDefinition(document.RootElement, options); } - internal static FunctionToolDefinition DeserializeFunctionToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static FunctionToolDefinition DeserializeFunctionToolDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalFunctionDefinition function = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "function"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalFunctionDefinition internalFunction = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("function"u8)) + if (prop.NameEquals("type"u8)) { - function = InternalFunctionDefinition.DeserializeInternalFunctionDefinition(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("function"u8)) { - type = property.Value.GetString(); + internalFunction = InternalFunctionDefinition.DeserializeInternalFunctionDefinition(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new FunctionToolDefinition(type, serializedAdditionalRawData, function); + return new FunctionToolDefinition(@type, additionalBinaryDataProperties, internalFunction); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +84,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - FunctionToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FunctionToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (FunctionToolDefinition)PersistableModelCreateCore(data, options); + protected override ToolDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFunctionToolDefinition(document.RootElement, options); } default: @@ -89,15 +103,20 @@ FunctionToolDefinition IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new FunctionToolDefinition FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(FunctionToolDefinition functionToolDefinition) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeFunctionToolDefinition(document.RootElement); + if (functionToolDefinition == null) + { + return null; + } + return BinaryContent.Create(functionToolDefinition, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator FunctionToolDefinition(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeFunctionToolDefinition(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/FunctionToolDefinition.cs b/src/Generated/Models/FunctionToolDefinition.cs index a1ed5ea67..fa9087663 100644 --- a/src/Generated/Models/FunctionToolDefinition.cs +++ b/src/Generated/Models/FunctionToolDefinition.cs @@ -2,9 +2,6 @@ #nullable disable -using System; -using System.Collections.Generic; - namespace OpenAI.Assistants { public partial class FunctionToolDefinition : ToolDefinition diff --git a/src/Generated/Models/GeneratedImage.Serialization.cs b/src/Generated/Models/GeneratedImage.Serialization.cs index cdcba781c..a89305aef 100644 --- a/src/Generated/Models/GeneratedImage.Serialization.cs +++ b/src/Generated/Models/GeneratedImage.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Images { @@ -14,31 +15,36 @@ public partial class GeneratedImage : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(GeneratedImage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("b64_json") != true && Optional.IsDefined(ImageBytes)) + if (Optional.IsDefined(RevisedPrompt) && _additionalBinaryDataProperties?.ContainsKey("revised_prompt") != true) + { + writer.WritePropertyName("revised_prompt"u8); + writer.WriteStringValue(RevisedPrompt); + } + if (Optional.IsDefined(ImageBytes) && _additionalBinaryDataProperties?.ContainsKey("b64_json") != true) { writer.WritePropertyName("b64_json"u8); writer.WriteBase64StringValue(ImageBytes.ToArray(), "D"); } - if (SerializedAdditionalRawData?.ContainsKey("url") != true && Optional.IsDefined(ImageUri)) + if (Optional.IsDefined(ImageUri) && _additionalBinaryDataProperties?.ContainsKey("url") != true) { writer.WritePropertyName("url"u8); writer.WriteStringValue(ImageUri.AbsoluteUri); } - if (SerializedAdditionalRawData?.ContainsKey("revised_prompt") != true && Optional.IsDefined(RevisedPrompt)) - { - writer.WritePropertyName("revised_prompt"u8); - writer.WriteStringValue(RevisedPrompt); - } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,73 +61,69 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp #endif } } - writer.WriteEndObject(); } - GeneratedImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + GeneratedImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual GeneratedImage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(GeneratedImage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeGeneratedImage(document.RootElement, options); } - internal static GeneratedImage DeserializeGeneratedImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static GeneratedImage DeserializeGeneratedImage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - BinaryData b64Json = default; - Uri url = default; string revisedPrompt = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData imageBytes = default; + Uri imageUri = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("b64_json"u8)) + if (prop.NameEquals("revised_prompt"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - b64Json = BinaryData.FromBytes(property.Value.GetBytesFromBase64("D")); + revisedPrompt = prop.Value.GetString(); continue; } - if (property.NameEquals("url"u8)) + if (prop.NameEquals("b64_json"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - url = new Uri(property.Value.GetString()); + imageBytes = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } - if (property.NameEquals("revised_prompt"u8)) + if (prop.NameEquals("url"u8)) { - revisedPrompt = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + imageUri = new Uri(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new GeneratedImage(b64Json, url, revisedPrompt, serializedAdditionalRawData); + return new GeneratedImage(revisedPrompt, imageBytes, imageUri, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -131,15 +133,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - GeneratedImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + GeneratedImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual GeneratedImage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeGeneratedImage(document.RootElement, options); } default: @@ -149,15 +152,20 @@ GeneratedImage IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static GeneratedImage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(GeneratedImage generatedImage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeGeneratedImage(document.RootElement); + if (generatedImage == null) + { + return null; + } + return BinaryContent.Create(generatedImage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator GeneratedImage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeGeneratedImage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/GeneratedImage.cs b/src/Generated/Models/GeneratedImage.cs index 9177bfc96..824838852 100644 --- a/src/Generated/Models/GeneratedImage.cs +++ b/src/Generated/Models/GeneratedImage.cs @@ -9,18 +9,26 @@ namespace OpenAI.Images { public partial class GeneratedImage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal GeneratedImage() { } - internal GeneratedImage(BinaryData imageBytes, Uri imageUri, string revisedPrompt, IDictionary serializedAdditionalRawData) + internal GeneratedImage(string revisedPrompt, BinaryData imageBytes, Uri imageUri, IDictionary additionalBinaryDataProperties) { + RevisedPrompt = revisedPrompt; ImageBytes = imageBytes; ImageUri = imageUri; - RevisedPrompt = revisedPrompt; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string RevisedPrompt { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/GeneratedImageCollection.Serialization.cs b/src/Generated/Models/GeneratedImageCollection.Serialization.cs index 46bcc4d4e..b58c56430 100644 --- a/src/Generated/Models/GeneratedImageCollection.Serialization.cs +++ b/src/Generated/Models/GeneratedImageCollection.Serialization.cs @@ -6,27 +6,63 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Images { public partial class GeneratedImageCollection : IJsonModel { - GeneratedImageCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(GeneratedImageCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(GeneratedImageCollection)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) + { + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(CreatedAt, "U"); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + GeneratedImageCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual GeneratedImageCollection 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(GeneratedImageCollection)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeGeneratedImageCollection(document.RootElement, options); + return GeneratedImageCollection.DeserializeGeneratedImageCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +72,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - GeneratedImageCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + GeneratedImageCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual GeneratedImageCollection 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeGeneratedImageCollection(document.RootElement, options); + return GeneratedImageCollection.DeserializeGeneratedImageCollection(document.RootElement, options); } default: throw new FormatException($"The model {nameof(GeneratedImageCollection)} does not support reading '{options.Format}' format."); @@ -54,15 +91,20 @@ GeneratedImageCollection IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static GeneratedImageCollection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(GeneratedImageCollection generatedImageCollection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeGeneratedImageCollection(document.RootElement); + if (generatedImageCollection == null) + { + return null; + } + return BinaryContent.Create(generatedImageCollection, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator GeneratedImageCollection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return GeneratedImageCollection.DeserializeGeneratedImageCollection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/GeneratedImageCollection.cs b/src/Generated/Models/GeneratedImageCollection.cs index 992b8ad42..7446dd1af 100644 --- a/src/Generated/Models/GeneratedImageCollection.cs +++ b/src/Generated/Models/GeneratedImageCollection.cs @@ -4,12 +4,17 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; namespace OpenAI.Images { - public partial class GeneratedImageCollection : ReadOnlyCollection + public partial class GeneratedImageCollection { + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/GeneratedImageFormat.cs b/src/Generated/Models/GeneratedImageFormat.cs index ff4ede1c5..51076da91 100644 --- a/src/Generated/Models/GeneratedImageFormat.cs +++ b/src/Generated/Models/GeneratedImageFormat.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { public readonly partial struct GeneratedImageFormat : IEquatable { private readonly string _value; + private const string UrlValue = "url"; + private const string B64JsonValue = "b64_json"; public GeneratedImageFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string UriValue = "url"; - private const string BytesValue = "b64_json"; public static bool operator ==(GeneratedImageFormat left, GeneratedImageFormat right) => left.Equals(right); + public static bool operator !=(GeneratedImageFormat left, GeneratedImageFormat right) => !left.Equals(right); + public static implicit operator GeneratedImageFormat(string value) => new GeneratedImageFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedImageFormat other && Equals(other); + public bool Equals(GeneratedImageFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/GeneratedImageQuality.cs b/src/Generated/Models/GeneratedImageQuality.cs index fb53a9853..030295c0b 100644 --- a/src/Generated/Models/GeneratedImageQuality.cs +++ b/src/Generated/Models/GeneratedImageQuality.cs @@ -4,32 +4,39 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { public readonly partial struct GeneratedImageQuality : IEquatable { private readonly string _value; + private const string StandardValue = "standard"; + private const string HdValue = "hd"; public GeneratedImageQuality(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string StandardValue = "standard"; - private const string HighValue = "hd"; + _value = value; + } public static GeneratedImageQuality Standard { get; } = new GeneratedImageQuality(StandardValue); + public static bool operator ==(GeneratedImageQuality left, GeneratedImageQuality right) => left.Equals(right); + public static bool operator !=(GeneratedImageQuality left, GeneratedImageQuality right) => !left.Equals(right); + public static implicit operator GeneratedImageQuality(string value) => new GeneratedImageQuality(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedImageQuality other && Equals(other); + public bool Equals(GeneratedImageQuality other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/GeneratedImageSize.cs b/src/Generated/Models/GeneratedImageSize.cs index 8a16802ab..ae5e05493 100644 --- a/src/Generated/Models/GeneratedImageSize.cs +++ b/src/Generated/Models/GeneratedImageSize.cs @@ -9,20 +9,25 @@ namespace OpenAI.Images { public readonly partial struct GeneratedImageSize : IEquatable { - private const string W256xH256Value = "256x256"; - private const string W512xH512Value = "512x512"; - private const string W1024xH1024Value = "1024x1024"; - private const string W1024xH1792Value = "1792x1024"; - private const string W1792xH1024Value = "1024x1792"; + private readonly string _value; + private const string _256x256Value = "256x256"; + private const string _512x512Value = "512x512"; + private const string _1024x1024Value = "1024x1024"; + private const string _1792x1024Value = "1792x1024"; + private const string _1024x1792Value = "1024x1792"; + public static bool operator ==(GeneratedImageSize left, GeneratedImageSize right) => left.Equals(right); + public static bool operator !=(GeneratedImageSize left, GeneratedImageSize right) => !left.Equals(right); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedImageSize other && Equals(other); + public bool Equals(GeneratedImageSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/GeneratedImageStyle.cs b/src/Generated/Models/GeneratedImageStyle.cs index 5a68da2bf..1b16f5bc3 100644 --- a/src/Generated/Models/GeneratedImageStyle.cs +++ b/src/Generated/Models/GeneratedImageStyle.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { public readonly partial struct GeneratedImageStyle : IEquatable { private readonly string _value; + private const string VividValue = "vivid"; + private const string NaturalValue = "natural"; public GeneratedImageStyle(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VividValue = "vivid"; - private const string NaturalValue = "natural"; + _value = value; + } public static GeneratedImageStyle Vivid { get; } = new GeneratedImageStyle(VividValue); + public static GeneratedImageStyle Natural { get; } = new GeneratedImageStyle(NaturalValue); + public static bool operator ==(GeneratedImageStyle left, GeneratedImageStyle right) => left.Equals(right); + public static bool operator !=(GeneratedImageStyle left, GeneratedImageStyle right) => !left.Equals(right); + public static implicit operator GeneratedImageStyle(string value) => new GeneratedImageStyle(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedImageStyle other && Equals(other); + public bool Equals(GeneratedImageStyle other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/GeneratedSpeechFormat.cs b/src/Generated/Models/GeneratedSpeechFormat.cs index e8c256e31..d1eebe036 100644 --- a/src/Generated/Models/GeneratedSpeechFormat.cs +++ b/src/Generated/Models/GeneratedSpeechFormat.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { public readonly partial struct GeneratedSpeechFormat : IEquatable { private readonly string _value; - - public GeneratedSpeechFormat(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string Mp3Value = "mp3"; private const string OpusValue = "opus"; private const string AacValue = "aac"; @@ -23,22 +18,39 @@ public GeneratedSpeechFormat(string value) private const string WavValue = "wav"; private const string PcmValue = "pcm"; + public GeneratedSpeechFormat(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static GeneratedSpeechFormat Mp3 { get; } = new GeneratedSpeechFormat(Mp3Value); + public static GeneratedSpeechFormat Opus { get; } = new GeneratedSpeechFormat(OpusValue); + public static GeneratedSpeechFormat Aac { get; } = new GeneratedSpeechFormat(AacValue); + public static GeneratedSpeechFormat Flac { get; } = new GeneratedSpeechFormat(FlacValue); + public static GeneratedSpeechFormat Wav { get; } = new GeneratedSpeechFormat(WavValue); + public static GeneratedSpeechFormat Pcm { get; } = new GeneratedSpeechFormat(PcmValue); + public static bool operator ==(GeneratedSpeechFormat left, GeneratedSpeechFormat right) => left.Equals(right); + public static bool operator !=(GeneratedSpeechFormat left, GeneratedSpeechFormat right) => !left.Equals(right); + public static implicit operator GeneratedSpeechFormat(string value) => new GeneratedSpeechFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedSpeechFormat other && Equals(other); + public bool Equals(GeneratedSpeechFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/GeneratedSpeechVoice.cs b/src/Generated/Models/GeneratedSpeechVoice.cs index 14fad7425..7f18f9eed 100644 --- a/src/Generated/Models/GeneratedSpeechVoice.cs +++ b/src/Generated/Models/GeneratedSpeechVoice.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { public readonly partial struct GeneratedSpeechVoice : IEquatable { private readonly string _value; - - public GeneratedSpeechVoice(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string AlloyValue = "alloy"; private const string EchoValue = "echo"; private const string FableValue = "fable"; @@ -23,22 +18,39 @@ public GeneratedSpeechVoice(string value) private const string NovaValue = "nova"; private const string ShimmerValue = "shimmer"; + public GeneratedSpeechVoice(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static GeneratedSpeechVoice Alloy { get; } = new GeneratedSpeechVoice(AlloyValue); + public static GeneratedSpeechVoice Echo { get; } = new GeneratedSpeechVoice(EchoValue); + public static GeneratedSpeechVoice Fable { get; } = new GeneratedSpeechVoice(FableValue); + public static GeneratedSpeechVoice Onyx { get; } = new GeneratedSpeechVoice(OnyxValue); + public static GeneratedSpeechVoice Nova { get; } = new GeneratedSpeechVoice(NovaValue); + public static GeneratedSpeechVoice Shimmer { get; } = new GeneratedSpeechVoice(ShimmerValue); + public static bool operator ==(GeneratedSpeechVoice left, GeneratedSpeechVoice right) => left.Equals(right); + public static bool operator !=(GeneratedSpeechVoice left, GeneratedSpeechVoice right) => !left.Equals(right); + public static implicit operator GeneratedSpeechVoice(string value) => new GeneratedSpeechVoice(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is GeneratedSpeechVoice other && Equals(other); + public bool Equals(GeneratedSpeechVoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/HyperparameterBatchSize.cs b/src/Generated/Models/HyperparameterBatchSize.cs index c0fc1a7ec..b223df728 100644 --- a/src/Generated/Models/HyperparameterBatchSize.cs +++ b/src/Generated/Models/HyperparameterBatchSize.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct HyperparameterBatchSize : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public HyperparameterBatchSize(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static HyperparameterBatchSize Auto { get; } = new HyperparameterBatchSize(AutoValue); + public static bool operator ==(HyperparameterBatchSize left, HyperparameterBatchSize right) => left.Equals(right); + public static bool operator !=(HyperparameterBatchSize left, HyperparameterBatchSize right) => !left.Equals(right); + public static implicit operator HyperparameterBatchSize(string value) => new HyperparameterBatchSize(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is HyperparameterBatchSize other && Equals(other); + public bool Equals(HyperparameterBatchSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/HyperparameterCycleCount.cs b/src/Generated/Models/HyperparameterCycleCount.cs index 3f55bc831..12306c291 100644 --- a/src/Generated/Models/HyperparameterCycleCount.cs +++ b/src/Generated/Models/HyperparameterCycleCount.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct HyperparameterCycleCount : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public HyperparameterCycleCount(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static HyperparameterCycleCount Auto { get; } = new HyperparameterCycleCount(AutoValue); + public static bool operator ==(HyperparameterCycleCount left, HyperparameterCycleCount right) => left.Equals(right); + public static bool operator !=(HyperparameterCycleCount left, HyperparameterCycleCount right) => !left.Equals(right); + public static implicit operator HyperparameterCycleCount(string value) => new HyperparameterCycleCount(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is HyperparameterCycleCount other && Equals(other); + public bool Equals(HyperparameterCycleCount other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/HyperparameterLearningRate.cs b/src/Generated/Models/HyperparameterLearningRate.cs index a40fbb8d6..58643912a 100644 --- a/src/Generated/Models/HyperparameterLearningRate.cs +++ b/src/Generated/Models/HyperparameterLearningRate.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct HyperparameterLearningRate : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; public HyperparameterLearningRate(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; + _value = value; + } public static HyperparameterLearningRate Auto { get; } = new HyperparameterLearningRate(AutoValue); + public static bool operator ==(HyperparameterLearningRate left, HyperparameterLearningRate right) => left.Equals(right); + public static bool operator !=(HyperparameterLearningRate left, HyperparameterLearningRate right) => !left.Equals(right); + public static implicit operator HyperparameterLearningRate(string value) => new HyperparameterLearningRate(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is HyperparameterLearningRate other && Equals(other); + public bool Equals(HyperparameterLearningRate other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/HyperparameterOptions.Serialization.cs b/src/Generated/Models/HyperparameterOptions.Serialization.cs index 6ccb44926..1e3d8a420 100644 --- a/src/Generated/Models/HyperparameterOptions.Serialization.cs +++ b/src/Generated/Models/HyperparameterOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { @@ -14,18 +15,23 @@ internal partial class HyperparameterOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(HyperparameterOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("n_epochs") != true && Optional.IsDefined(NEpochs)) + if (Optional.IsDefined(NEpochs) && _additionalBinaryDataProperties?.ContainsKey("n_epochs") != true) { writer.WritePropertyName("n_epochs"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(NEpochs); + writer.WriteRawValue(NEpochs); #else using (JsonDocument document = JsonDocument.Parse(NEpochs)) { @@ -33,11 +39,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } #endif } - if (SerializedAdditionalRawData?.ContainsKey("batch_size") != true && Optional.IsDefined(BatchSize)) + if (Optional.IsDefined(BatchSize) && _additionalBinaryDataProperties?.ContainsKey("batch_size") != true) { writer.WritePropertyName("batch_size"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(BatchSize); + writer.WriteRawValue(BatchSize); #else using (JsonDocument document = JsonDocument.Parse(BatchSize)) { @@ -45,11 +51,11 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } #endif } - if (SerializedAdditionalRawData?.ContainsKey("learning_rate_multiplier") != true && Optional.IsDefined(LearningRateMultiplier)) + if (Optional.IsDefined(LearningRateMultiplier) && _additionalBinaryDataProperties?.ContainsKey("learning_rate_multiplier") != true) { writer.WritePropertyName("learning_rate_multiplier"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(LearningRateMultiplier); + writer.WriteRawValue(LearningRateMultiplier); #else using (JsonDocument document = JsonDocument.Parse(LearningRateMultiplier)) { @@ -57,9 +63,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -67,7 +73,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -76,25 +82,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - HyperparameterOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + HyperparameterOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual HyperparameterOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(HyperparameterOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeHyperparameterOptions(document.RootElement, options); } - internal static HyperparameterOptions DeserializeHyperparameterOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static HyperparameterOptions DeserializeHyperparameterOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -102,51 +106,49 @@ internal static HyperparameterOptions DeserializeHyperparameterOptions(JsonEleme BinaryData nEpochs = default; BinaryData batchSize = default; BinaryData learningRateMultiplier = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("n_epochs"u8)) + if (prop.NameEquals("n_epochs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - nEpochs = BinaryData.FromString(property.Value.GetRawText()); + nEpochs = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("batch_size"u8)) + if (prop.NameEquals("batch_size"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - batchSize = BinaryData.FromString(property.Value.GetRawText()); + batchSize = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("learning_rate_multiplier"u8)) + if (prop.NameEquals("learning_rate_multiplier"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - learningRateMultiplier = BinaryData.FromString(property.Value.GetRawText()); + learningRateMultiplier = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new HyperparameterOptions(nEpochs, batchSize, learningRateMultiplier, serializedAdditionalRawData); + return new HyperparameterOptions(nEpochs, batchSize, learningRateMultiplier, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -156,15 +158,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - HyperparameterOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + HyperparameterOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual HyperparameterOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeHyperparameterOptions(document.RootElement, options); } default: @@ -174,15 +177,20 @@ HyperparameterOptions IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static HyperparameterOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(HyperparameterOptions hyperparameterOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeHyperparameterOptions(document.RootElement); + if (hyperparameterOptions == null) + { + return null; + } + return BinaryContent.Create(hyperparameterOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator HyperparameterOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeHyperparameterOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/HyperparameterOptions.cs b/src/Generated/Models/HyperparameterOptions.cs index 06e35aa06..bf3cd076e 100644 --- a/src/Generated/Models/HyperparameterOptions.cs +++ b/src/Generated/Models/HyperparameterOptions.cs @@ -9,21 +9,30 @@ namespace OpenAI.FineTuning { internal partial class HyperparameterOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public HyperparameterOptions() { } - internal HyperparameterOptions(BinaryData nEpochs, BinaryData batchSize, BinaryData learningRateMultiplier, IDictionary serializedAdditionalRawData) + internal HyperparameterOptions(BinaryData nEpochs, BinaryData batchSize, BinaryData learningRateMultiplier, IDictionary additionalBinaryDataProperties) { NEpochs = nEpochs; BatchSize = batchSize; LearningRateMultiplier = learningRateMultiplier; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public BinaryData NEpochs { get; set; } + public BinaryData BatchSize { get; set; } + public BinaryData LearningRateMultiplier { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ImageEditOptions.Serialization.cs b/src/Generated/Models/ImageEditOptions.Serialization.cs index 0595ecc63..4b56a9f0a 100644 --- a/src/Generated/Models/ImageEditOptions.Serialization.cs +++ b/src/Generated/Models/ImageEditOptions.Serialization.cs @@ -6,8 +6,8 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; -using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Images { @@ -15,55 +15,46 @@ public partial class ImageEditOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ImageEditOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("image") != true) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { - writer.WritePropertyName("image"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Image); -#else - using (JsonDocument document = JsonDocument.Parse(Image)) + if (Model != null) { - JsonSerializer.Serialize(writer, document.RootElement); + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model.Value.ToString()); + } + else + { + writer.WriteNull("model"u8); } -#endif } - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true) + if (_additionalBinaryDataProperties?.ContainsKey("image") != true) + { + writer.WritePropertyName("image"u8); + writer.WriteBase64StringValue(Image.ToArray(), "D"); + } + if (_additionalBinaryDataProperties?.ContainsKey("prompt") != true) { writer.WritePropertyName("prompt"u8); writer.WriteStringValue(Prompt); } - if (SerializedAdditionalRawData?.ContainsKey("mask") != true && Optional.IsDefined(Mask)) + if (Optional.IsDefined(Mask) && _additionalBinaryDataProperties?.ContainsKey("mask") != true) { writer.WritePropertyName("mask"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Mask); -#else - using (JsonDocument document = JsonDocument.Parse(Mask)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) - { - if (Model != null) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model.Value.ToString()); - } - else - { - writer.WriteNull("model"); - } + writer.WriteBase64StringValue(Mask.ToArray(), "D"); } - if (SerializedAdditionalRawData?.ContainsKey("n") != true && Optional.IsDefined(N)) + if (Optional.IsDefined(N) && _additionalBinaryDataProperties?.ContainsKey("n") != true) { if (N != null) { @@ -72,10 +63,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } else { - writer.WriteNull("n"); + writer.WriteNull("n"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("size") != true && Optional.IsDefined(Size)) + if (Optional.IsDefined(Size) && _additionalBinaryDataProperties?.ContainsKey("size") != true) { if (Size != null) { @@ -84,10 +75,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } else { - writer.WriteNull("size"); + writer.WriteNull("size"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { if (ResponseFormat != null) { @@ -96,17 +87,17 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } else { - writer.WriteNull("response_format"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) + if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true) { writer.WritePropertyName("user"u8); writer.WriteStringValue(EndUserId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -114,7 +105,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -123,207 +114,143 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - ImageEditOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageEditOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ImageEditOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ImageEditOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeImageEditOptions(document.RootElement, options); } - internal static ImageEditOptions DeserializeImageEditOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageEditOptions DeserializeImageEditOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalCreateImageEditRequestModel? model = default; BinaryData image = default; string prompt = default; BinaryData mask = default; - InternalCreateImageEditRequestModel? model = default; long? n = default; GeneratedImageSize? size = default; GeneratedImageFormat? responseFormat = default; - string user = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string endUserId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("image"u8)) + if (prop.NameEquals("model"u8)) { - image = BinaryData.FromString(property.Value.GetRawText()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + model = null; + continue; + } + model = new InternalCreateImageEditRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("prompt"u8)) + if (prop.NameEquals("image"u8)) { - prompt = property.Value.GetString(); + image = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } - if (property.NameEquals("mask"u8)) + if (prop.NameEquals("prompt"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - mask = BinaryData.FromString(property.Value.GetRawText()); + prompt = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("mask"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - model = null; continue; } - model = new InternalCreateImageEditRequestModel(property.Value.GetString()); + mask = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } - if (property.NameEquals("n"u8)) + if (prop.NameEquals("n"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { n = null; continue; } - n = property.Value.GetInt64(); + n = prop.Value.GetInt64(); continue; } - if (property.NameEquals("size"u8)) + if (prop.NameEquals("size"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { size = null; continue; } - size = new GeneratedImageSize(property.Value.GetString()); + size = new GeneratedImageSize(prop.Value.GetString()); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { responseFormat = null; continue; } - responseFormat = new GeneratedImageFormat(property.Value.GetString()); + responseFormat = new GeneratedImageFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("user"u8)) { - user = property.Value.GetString(); + endUserId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ImageEditOptions( + model, image, prompt, mask, - model, n, size, responseFormat, - user, - serializedAdditionalRawData); + endUserId, + additionalBinaryDataProperties); } - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(Image, "image", "image"); - content.Add(Prompt, "prompt"); - if (Optional.IsDefined(Mask)) - { - content.Add(Mask, "mask", "mask"); - } - if (Optional.IsDefined(Model)) - { - if (Model != null) - { - content.Add(Model.Value.ToString(), "model"); - } - } - if (Optional.IsDefined(N)) - { - if (N != null) - { - content.Add(N.Value, "n"); - } - } - if (Optional.IsDefined(Size)) - { - if (Size != null) - { - content.Add(Size.Value.ToString(), "size"); - } - } - if (Optional.IsDefined(ResponseFormat)) - { - if (ResponseFormat != null) - { - content.Add(ResponseFormat.Value.ToString(), "response_format"); - } - } - if (Optional.IsDefined(EndUserId)) - { - content.Add(EndUserId, "user"); - } - return content; - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(ImageEditOptions)} does not support writing '{options.Format}' format."); } } - ImageEditOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ImageEditOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ImageEditOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeImageEditOptions(document.RootElement, options); } default: @@ -331,17 +258,22 @@ ImageEditOptions IPersistableModel.Create(BinaryData data, Mod } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ImageEditOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ImageEditOptions imageEditOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeImageEditOptions(document.RootElement); + if (imageEditOptions == null) + { + return null; + } + return BinaryContent.Create(imageEditOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ImageEditOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeImageEditOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ImageEditOptions.cs b/src/Generated/Models/ImageEditOptions.cs index c46d7879c..c204556ea 100644 --- a/src/Generated/Models/ImageEditOptions.cs +++ b/src/Generated/Models/ImageEditOptions.cs @@ -9,19 +9,25 @@ namespace OpenAI.Images { public partial class ImageEditOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ImageEditOptions(BinaryData image, string prompt, BinaryData mask, InternalCreateImageEditRequestModel? model, long? n, GeneratedImageSize? size, GeneratedImageFormat? responseFormat, string endUserId, IDictionary serializedAdditionalRawData) + internal ImageEditOptions(InternalCreateImageEditRequestModel? model, BinaryData image, string prompt, BinaryData mask, long? n, GeneratedImageSize? size, GeneratedImageFormat? responseFormat, string endUserId, IDictionary additionalBinaryDataProperties) { + Model = model; Image = image; Prompt = prompt; Mask = mask; - Model = model; N = n; Size = size; ResponseFormat = responseFormat; EndUserId = endUserId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ImageGenerationOptions.Serialization.cs b/src/Generated/Models/ImageGenerationOptions.Serialization.cs index 386ee3b6a..cb8f165d3 100644 --- a/src/Generated/Models/ImageGenerationOptions.Serialization.cs +++ b/src/Generated/Models/ImageGenerationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Images { @@ -14,91 +15,96 @@ public partial class ImageGenerationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ImageGenerationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true) + if (Optional.IsDefined(Quality) && _additionalBinaryDataProperties?.ContainsKey("quality") != true) { - writer.WritePropertyName("prompt"u8); - writer.WriteStringValue(Prompt); + writer.WritePropertyName("quality"u8); + writer.WriteStringValue(Quality.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { - if (Model != null) + if (ResponseFormat != null) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model.Value.ToString()); + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); } else { - writer.WriteNull("model"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("n") != true && Optional.IsDefined(N)) + if (Optional.IsDefined(Size) && _additionalBinaryDataProperties?.ContainsKey("size") != true) { - if (N != null) + if (Size != null) { - writer.WritePropertyName("n"u8); - writer.WriteNumberValue(N.Value); + writer.WritePropertyName("size"u8); + writer.WriteStringValue(Size.Value.ToString()); } else { - writer.WriteNull("n"); + writer.WriteNull("size"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("quality") != true && Optional.IsDefined(Quality)) - { - writer.WritePropertyName("quality"u8); - writer.WriteStringValue(Quality.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(Style) && _additionalBinaryDataProperties?.ContainsKey("style") != true) { - if (ResponseFormat != null) + if (Style != null) { - writer.WritePropertyName("response_format"u8); - writer.WriteStringValue(ResponseFormat.Value.ToString()); + writer.WritePropertyName("style"u8); + writer.WriteStringValue(Style.Value.ToString()); } else { - writer.WriteNull("response_format"); + writer.WriteNull("style"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("size") != true && Optional.IsDefined(Size)) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { - if (Size != null) + if (Model != null) { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size.Value.ToString()); + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model.Value.ToString()); } else { - writer.WriteNull("size"); + writer.WriteNull("model"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("style") != true && Optional.IsDefined(Style)) + if (_additionalBinaryDataProperties?.ContainsKey("prompt") != true) { - if (Style != null) + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + } + if (Optional.IsDefined(N) && _additionalBinaryDataProperties?.ContainsKey("n") != true) + { + if (N != null) { - writer.WritePropertyName("style"u8); - writer.WriteStringValue(Style.Value.ToString()); + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(N.Value); } else { - writer.WriteNull("style"); + writer.WriteNull("n"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) + if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true) { writer.WritePropertyName("user"u8); writer.WriteStringValue(EndUserId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -106,7 +112,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -115,133 +121,129 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader #endif } } - writer.WriteEndObject(); } - ImageGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ImageGenerationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeImageGenerationOptions(document.RootElement, options); } - internal static ImageGenerationOptions DeserializeImageGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageGenerationOptions DeserializeImageGenerationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string prompt = default; - InternalCreateImageRequestModel? model = default; - long? n = default; GeneratedImageQuality? quality = default; GeneratedImageFormat? responseFormat = default; GeneratedImageSize? size = default; GeneratedImageStyle? style = default; - string user = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalCreateImageRequestModel? model = default; + string prompt = default; + long? n = default; + string endUserId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("prompt"u8)) + if (prop.NameEquals("quality"u8)) { - prompt = property.Value.GetString(); - continue; - } - if (property.NameEquals("model"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - model = null; continue; } - model = new InternalCreateImageRequestModel(property.Value.GetString()); + quality = new GeneratedImageQuality(prop.Value.GetString()); continue; } - if (property.NameEquals("n"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - n = null; + responseFormat = null; continue; } - n = property.Value.GetInt64(); + responseFormat = new GeneratedImageFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("quality"u8)) + if (prop.NameEquals("size"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + size = null; continue; } - quality = new GeneratedImageQuality(property.Value.GetString()); + size = new GeneratedImageSize(prop.Value.GetString()); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("style"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + style = null; continue; } - responseFormat = new GeneratedImageFormat(property.Value.GetString()); + style = new GeneratedImageStyle(prop.Value.GetString()); continue; } - if (property.NameEquals("size"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - size = null; + model = null; continue; } - size = new GeneratedImageSize(property.Value.GetString()); + model = new InternalCreateImageRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("style"u8)) + if (prop.NameEquals("prompt"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + prompt = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("n"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - style = null; + n = null; continue; } - style = new GeneratedImageStyle(property.Value.GetString()); + n = prop.Value.GetInt64(); continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("user"u8)) { - user = property.Value.GetString(); + endUserId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ImageGenerationOptions( - prompt, - model, - n, quality, responseFormat, size, style, - user, - serializedAdditionalRawData); + model, + prompt, + n, + endUserId, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -251,15 +253,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - ImageGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ImageGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ImageGenerationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeImageGenerationOptions(document.RootElement, options); } default: @@ -269,15 +272,20 @@ ImageGenerationOptions IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ImageGenerationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ImageGenerationOptions imageGenerationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeImageGenerationOptions(document.RootElement); + if (imageGenerationOptions == null) + { + return null; + } + return BinaryContent.Create(imageGenerationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ImageGenerationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeImageGenerationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ImageGenerationOptions.cs b/src/Generated/Models/ImageGenerationOptions.cs index e7d9311dc..f38aeba44 100644 --- a/src/Generated/Models/ImageGenerationOptions.cs +++ b/src/Generated/Models/ImageGenerationOptions.cs @@ -9,23 +9,33 @@ namespace OpenAI.Images { public partial class ImageGenerationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ImageGenerationOptions(string prompt, InternalCreateImageRequestModel? model, long? n, GeneratedImageQuality? quality, GeneratedImageFormat? responseFormat, GeneratedImageSize? size, GeneratedImageStyle? style, string endUserId, IDictionary serializedAdditionalRawData) + internal ImageGenerationOptions(GeneratedImageQuality? quality, GeneratedImageFormat? responseFormat, GeneratedImageSize? size, GeneratedImageStyle? style, InternalCreateImageRequestModel? model, string prompt, long? n, string endUserId, IDictionary additionalBinaryDataProperties) { - Prompt = prompt; - Model = model; - N = n; Quality = quality; ResponseFormat = responseFormat; Size = size; Style = style; + Model = model; + Prompt = prompt; + N = n; EndUserId = endUserId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public GeneratedImageQuality? Quality { get; set; } + public GeneratedImageFormat? ResponseFormat { get; set; } + public GeneratedImageSize? Size { get; set; } + public GeneratedImageStyle? Style { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ImageVariationOptions.Serialization.cs b/src/Generated/Models/ImageVariationOptions.Serialization.cs index 38d3c0758..860fa87f2 100644 --- a/src/Generated/Models/ImageVariationOptions.Serialization.cs +++ b/src/Generated/Models/ImageVariationOptions.Serialization.cs @@ -6,8 +6,8 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; -using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Images { @@ -15,26 +15,19 @@ public partial class ImageVariationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ImageVariationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("image") != true) - { - writer.WritePropertyName("image"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Image); -#else - using (JsonDocument document = JsonDocument.Parse(Image)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { if (Model != null) { @@ -43,10 +36,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } else { - writer.WriteNull("model"); + writer.WriteNull("model"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("n") != true && Optional.IsDefined(N)) + if (_additionalBinaryDataProperties?.ContainsKey("image") != true) + { + writer.WritePropertyName("image"u8); + writer.WriteBase64StringValue(Image.ToArray(), "D"); + } + if (Optional.IsDefined(N) && _additionalBinaryDataProperties?.ContainsKey("n") != true) { if (N != null) { @@ -55,41 +53,41 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } else { - writer.WriteNull("n"); + writer.WriteNull("n"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(Size) && _additionalBinaryDataProperties?.ContainsKey("size") != true) { - if (ResponseFormat != null) + if (Size != null) { - writer.WritePropertyName("response_format"u8); - writer.WriteStringValue(ResponseFormat.Value.ToString()); + writer.WritePropertyName("size"u8); + writer.WriteStringValue(Size.Value.ToString()); } else { - writer.WriteNull("response_format"); + writer.WriteNull("size"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("size") != true && Optional.IsDefined(Size)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { - if (Size != null) + if (ResponseFormat != null) { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size.Value.ToString()); + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); } else { - writer.WriteNull("size"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) + if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true) { writer.WritePropertyName("user"u8); writer.WriteStringValue(EndUserId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -97,7 +95,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -106,184 +104,125 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - ImageVariationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageVariationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ImageVariationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ImageVariationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeImageVariationOptions(document.RootElement, options); } - internal static ImageVariationOptions DeserializeImageVariationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageVariationOptions DeserializeImageVariationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - BinaryData image = default; InternalCreateImageVariationRequestModel? model = default; + BinaryData image = default; long? n = default; - GeneratedImageFormat? responseFormat = default; GeneratedImageSize? size = default; - string user = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + GeneratedImageFormat? responseFormat = default; + string endUserId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("image"u8)) + if (prop.NameEquals("model"u8)) { - image = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("model"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { model = null; continue; } - model = new InternalCreateImageVariationRequestModel(property.Value.GetString()); + model = new InternalCreateImageVariationRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("n"u8)) + if (prop.NameEquals("image"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + image = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); + continue; + } + if (prop.NameEquals("n"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { n = null; continue; } - n = property.Value.GetInt64(); + n = prop.Value.GetInt64(); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("size"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + size = null; continue; } - responseFormat = new GeneratedImageFormat(property.Value.GetString()); + size = new GeneratedImageSize(prop.Value.GetString()); continue; } - if (property.NameEquals("size"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - size = null; + responseFormat = null; continue; } - size = new GeneratedImageSize(property.Value.GetString()); + responseFormat = new GeneratedImageFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("user"u8)) { - user = property.Value.GetString(); + endUserId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ImageVariationOptions( - image, model, + image, n, - responseFormat, size, - user, - serializedAdditionalRawData); - } - - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } + responseFormat, + endUserId, + additionalBinaryDataProperties); } - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() - { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(Image, "image", "image"); - if (Optional.IsDefined(Model)) - { - if (Model != null) - { - content.Add(Model.Value.ToString(), "model"); - } - } - if (Optional.IsDefined(N)) - { - if (N != null) - { - content.Add(N.Value, "n"); - } - } - if (Optional.IsDefined(ResponseFormat)) - { - if (ResponseFormat != null) - { - content.Add(ResponseFormat.Value.ToString(), "response_format"); - } - } - if (Optional.IsDefined(Size)) - { - if (Size != null) - { - content.Add(Size.Value.ToString(), "size"); - } - } - if (Optional.IsDefined(EndUserId)) - { - content.Add(EndUserId, "user"); - } - return content; - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(ImageVariationOptions)} does not support writing '{options.Format}' format."); } } - ImageVariationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ImageVariationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ImageVariationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeImageVariationOptions(document.RootElement, options); } default: @@ -291,17 +230,22 @@ ImageVariationOptions IPersistableModel.Create(BinaryData } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ImageVariationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ImageVariationOptions imageVariationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeImageVariationOptions(document.RootElement); + if (imageVariationOptions == null) + { + return null; + } + return BinaryContent.Create(imageVariationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ImageVariationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeImageVariationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ImageVariationOptions.cs b/src/Generated/Models/ImageVariationOptions.cs index 6fac2f976..c86f3fe68 100644 --- a/src/Generated/Models/ImageVariationOptions.cs +++ b/src/Generated/Models/ImageVariationOptions.cs @@ -9,17 +9,23 @@ namespace OpenAI.Images { public partial class ImageVariationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ImageVariationOptions(BinaryData image, InternalCreateImageVariationRequestModel? model, long? n, GeneratedImageFormat? responseFormat, GeneratedImageSize? size, string endUserId, IDictionary serializedAdditionalRawData) + internal ImageVariationOptions(InternalCreateImageVariationRequestModel? model, BinaryData image, long? n, GeneratedImageSize? size, GeneratedImageFormat? responseFormat, string endUserId, IDictionary additionalBinaryDataProperties) { - Image = image; Model = model; + Image = image; N = n; - ResponseFormat = responseFormat; Size = size; + ResponseFormat = responseFormat; EndUserId = endUserId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs b/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs index f76b44afb..a8cfb5281 100644 --- a/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs +++ b/src/Generated/Models/InternalAddUploadPartRequest.Serialization.cs @@ -6,37 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; -using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { internal partial class InternalAddUploadPartRequest : IJsonModel { + internal InternalAddUploadPartRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAddUploadPartRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (_additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); -#else - using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data))) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif + writer.WriteBase64StringValue(Data.ToArray(), "D"); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -44,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -53,95 +55,68 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - InternalAddUploadPartRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAddUploadPartRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalAddUploadPartRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAddUploadPartRequest(document.RootElement, options); } - internal static InternalAddUploadPartRequest DeserializeInternalAddUploadPartRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAddUploadPartRequest DeserializeInternalAddUploadPartRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - Stream data = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData data = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { - data = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + data = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAddUploadPartRequest(data, serializedAdditionalRawData); + return new InternalAddUploadPartRequest(data, additionalBinaryDataProperties); } - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(Data, "data", "data", "application/octet-stream"); - return content; - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(InternalAddUploadPartRequest)} does not support writing '{options.Format}' format."); } } - InternalAddUploadPartRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAddUploadPartRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalAddUploadPartRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAddUploadPartRequest(document.RootElement, options); } default: @@ -149,17 +124,22 @@ InternalAddUploadPartRequest IPersistableModel.Cre } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalAddUploadPartRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAddUploadPartRequest internalAddUploadPartRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAddUploadPartRequest(document.RootElement); + if (internalAddUploadPartRequest == null) + { + return null; + } + return BinaryContent.Create(internalAddUploadPartRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalAddUploadPartRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAddUploadPartRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAddUploadPartRequest.cs b/src/Generated/Models/InternalAddUploadPartRequest.cs index f6035f34b..15e1c9f4b 100644 --- a/src/Generated/Models/InternalAddUploadPartRequest.cs +++ b/src/Generated/Models/InternalAddUploadPartRequest.cs @@ -4,30 +4,33 @@ using System; using System.Collections.Generic; -using System.IO; +using OpenAI; namespace OpenAI.Files { internal partial class InternalAddUploadPartRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } - public InternalAddUploadPartRequest(Stream data) + private protected IDictionary _additionalBinaryDataProperties; + + public InternalAddUploadPartRequest(BinaryData data) { Argument.AssertNotNull(data, nameof(data)); Data = data; } - internal InternalAddUploadPartRequest(Stream data, IDictionary serializedAdditionalRawData) + internal InternalAddUploadPartRequest(BinaryData data, IDictionary additionalBinaryDataProperties) { Data = data; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalAddUploadPartRequest() + public BinaryData Data { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public Stream Data { get; } } } diff --git a/src/Generated/Models/InternalAssistantObjectObject.cs b/src/Generated/Models/InternalAssistantObjectObject.cs index bb627c2bc..51276ac20 100644 --- a/src/Generated/Models/InternalAssistantObjectObject.cs +++ b/src/Generated/Models/InternalAssistantObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalAssistantObjectObject : IEquatable { private readonly string _value; + private const string AssistantValue = "assistant"; public InternalAssistantObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AssistantValue = "assistant"; + _value = value; + } public static InternalAssistantObjectObject Assistant { get; } = new InternalAssistantObjectObject(AssistantValue); + public static bool operator ==(InternalAssistantObjectObject left, InternalAssistantObjectObject right) => left.Equals(right); + public static bool operator !=(InternalAssistantObjectObject left, InternalAssistantObjectObject right) => !left.Equals(right); + public static implicit operator InternalAssistantObjectObject(string value) => new InternalAssistantObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalAssistantObjectObject other && Equals(other); + public bool Equals(InternalAssistantObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs b/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs index 80afbf5f6..cc5ef9d4a 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatJsonObject.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,84 +15,62 @@ internal partial class InternalAssistantResponseFormatJsonObject : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantResponseFormatJsonObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalAssistantResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatJsonObject)JsonModelCreateCore(ref reader, options); + + protected override AssistantResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantResponseFormatJsonObject(document.RootElement, options); } - internal static InternalAssistantResponseFormatJsonObject DeserializeInternalAssistantResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantResponseFormatJsonObject DeserializeInternalAssistantResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "json_object"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantResponseFormatJsonObject(type, serializedAdditionalRawData); + return new InternalAssistantResponseFormatJsonObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalAssistantResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatJsonObject)PersistableModelCreateCore(data, options); + protected override AssistantResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantResponseFormatJsonObject(document.RootElement, options); } default: @@ -118,5 +98,21 @@ InternalAssistantResponseFormatJsonObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + public static implicit operator BinaryContent(InternalAssistantResponseFormatJsonObject internalAssistantResponseFormatJsonObject) + { + if (internalAssistantResponseFormatJsonObject == null) + { + return null; + } + return BinaryContent.Create(internalAssistantResponseFormatJsonObject, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator InternalAssistantResponseFormatJsonObject(ClientResult result) + { + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantResponseFormatJsonObject(document.RootElement, ModelSerializationExtensions.WireOptions); + } } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs b/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs index 96c7e52ef..48b864882 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatJsonObject.cs @@ -9,12 +9,11 @@ namespace OpenAI.Assistants { internal partial class InternalAssistantResponseFormatJsonObject : AssistantResponseFormat { - public InternalAssistantResponseFormatJsonObject() + public InternalAssistantResponseFormatJsonObject() : base("json_object") { - Type = "json_object"; } - internal InternalAssistantResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalAssistantResponseFormatJsonObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs b/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs index 24865dbf9..b62b36879 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.Serialization.cs @@ -7,103 +7,86 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Internal; namespace OpenAI.Assistants { internal partial class InternalAssistantResponseFormatJsonSchema : IJsonModel { + internal InternalAssistantResponseFormatJsonSchema() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantResponseFormatJsonSchema)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("json_schema") != true) { writer.WritePropertyName("json_schema"u8); writer.WriteObjectValue(JsonSchema, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalAssistantResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatJsonSchema)JsonModelCreateCore(ref reader, options); + + protected override AssistantResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantResponseFormatJsonSchema)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantResponseFormatJsonSchema(document.RootElement, options); } - internal static InternalAssistantResponseFormatJsonSchema DeserializeInternalAssistantResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantResponseFormatJsonSchema DeserializeInternalAssistantResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "json_schema"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("json_schema"u8)) + if (prop.NameEquals("type"u8)) { - jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("json_schema"u8)) { - type = property.Value.GetString(); + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + return new InternalAssistantResponseFormatJsonSchema(@type, additionalBinaryDataProperties, jsonSchema); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -113,15 +96,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalAssistantResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatJsonSchema)PersistableModelCreateCore(data, options); + protected override AssistantResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantResponseFormatJsonSchema(document.RootElement, options); } default: @@ -130,5 +114,21 @@ InternalAssistantResponseFormatJsonSchema IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + public static implicit operator BinaryContent(InternalAssistantResponseFormatJsonSchema internalAssistantResponseFormatJsonSchema) + { + if (internalAssistantResponseFormatJsonSchema == null) + { + return null; + } + return BinaryContent.Create(internalAssistantResponseFormatJsonSchema, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator InternalAssistantResponseFormatJsonSchema(ClientResult result) + { + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantResponseFormatJsonSchema(document.RootElement, ModelSerializationExtensions.WireOptions); + } } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs b/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs index 68db77ffc..abe5b17c3 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatJsonSchema.cs @@ -4,29 +4,25 @@ using System; using System.Collections.Generic; +using OpenAI; using OpenAI.Internal; namespace OpenAI.Assistants { internal partial class InternalAssistantResponseFormatJsonSchema : AssistantResponseFormat { - public InternalAssistantResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + public InternalAssistantResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base("json_schema") { Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); - Type = "json_schema"; JsonSchema = jsonSchema; } - internal InternalAssistantResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + internal InternalAssistantResponseFormatJsonSchema(string @type, IDictionary additionalBinaryDataProperties, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(@type, additionalBinaryDataProperties) { JsonSchema = jsonSchema; } - internal InternalAssistantResponseFormatJsonSchema() - { - } - public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; } } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs b/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs index a2ae06eea..a7e939ffa 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatText.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,84 +15,62 @@ internal partial class InternalAssistantResponseFormatText : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantResponseFormatText)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalAssistantResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatText)JsonModelCreateCore(ref reader, options); + + protected override AssistantResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantResponseFormatText)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantResponseFormatText(document.RootElement, options); } - internal static InternalAssistantResponseFormatText DeserializeInternalAssistantResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantResponseFormatText DeserializeInternalAssistantResponseFormatText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "text"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantResponseFormatText(type, serializedAdditionalRawData); + return new InternalAssistantResponseFormatText(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - InternalAssistantResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAssistantResponseFormatText)PersistableModelCreateCore(data, options); + protected override AssistantResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantResponseFormatText(document.RootElement, options); } default: @@ -118,5 +98,21 @@ InternalAssistantResponseFormatText IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + public static implicit operator BinaryContent(InternalAssistantResponseFormatText internalAssistantResponseFormatText) + { + if (internalAssistantResponseFormatText == null) + { + return null; + } + return BinaryContent.Create(internalAssistantResponseFormatText, ModelSerializationExtensions.WireOptions); + } + + public static explicit operator InternalAssistantResponseFormatText(ClientResult result) + { + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantResponseFormatText(document.RootElement, ModelSerializationExtensions.WireOptions); + } } } diff --git a/src/Generated/Models/InternalAssistantResponseFormatText.cs b/src/Generated/Models/InternalAssistantResponseFormatText.cs index e2763f14c..82330418f 100644 --- a/src/Generated/Models/InternalAssistantResponseFormatText.cs +++ b/src/Generated/Models/InternalAssistantResponseFormatText.cs @@ -9,12 +9,11 @@ namespace OpenAI.Assistants { internal partial class InternalAssistantResponseFormatText : AssistantResponseFormat { - public InternalAssistantResponseFormatText() + public InternalAssistantResponseFormatText() : base("text") { - Type = "text"; } - internal InternalAssistantResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalAssistantResponseFormatText(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.Serialization.cs b/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.Serialization.cs index 7a8338608..efe91100e 100644 --- a/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.Serialization.cs +++ b/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalAssistantToolsFileSearchFileSearch : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantToolsFileSearchFileSearch)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("max_num_results") != true && Optional.IsDefined(InternalMaxNumResults)) - { - writer.WritePropertyName("max_num_results"u8); - writer.WriteNumberValue(InternalMaxNumResults.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("ranking_options") != true && Optional.IsDefined(RankingOptions)) + if (Optional.IsDefined(RankingOptions) && _additionalBinaryDataProperties?.ContainsKey("ranking_options") != true) { writer.WritePropertyName("ranking_options"u8); writer.WriteObjectValue(RankingOptions, options); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(InternalMaxNumResults) && _additionalBinaryDataProperties?.ContainsKey("max_num_results") != true) + { + writer.WritePropertyName("max_num_results"u8); + writer.WriteNumberValue(InternalMaxNumResults.Value); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalAssistantToolsFileSearchFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantToolsFileSearchFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalAssistantToolsFileSearchFileSearch JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantToolsFileSearchFileSearch)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantToolsFileSearchFileSearch(document.RootElement, options); } - internal static InternalAssistantToolsFileSearchFileSearch DeserializeInternalAssistantToolsFileSearchFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantToolsFileSearchFileSearch DeserializeInternalAssistantToolsFileSearchFileSearch(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int? maxNumResults = default; FileSearchRankingOptions rankingOptions = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int? internalMaxNumResults = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("max_num_results"u8)) + if (prop.NameEquals("ranking_options"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - maxNumResults = property.Value.GetInt32(); + rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(prop.Value, options); continue; } - if (property.NameEquals("ranking_options"u8)) + if (prop.NameEquals("max_num_results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(property.Value, options); + internalMaxNumResults = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantToolsFileSearchFileSearch(maxNumResults, rankingOptions, serializedAdditionalRawData); + return new InternalAssistantToolsFileSearchFileSearch(rankingOptions, internalMaxNumResults, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write(M } } - InternalAssistantToolsFileSearchFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantToolsFileSearchFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalAssistantToolsFileSearchFileSearch 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantToolsFileSearchFileSearch(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalAssistantToolsFileSearchFileSearch IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalAssistantToolsFileSearchFileSearch FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAssistantToolsFileSearchFileSearch internalAssistantToolsFileSearchFileSearch) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAssistantToolsFileSearchFileSearch(document.RootElement); + if (internalAssistantToolsFileSearchFileSearch == null) + { + return null; + } + return BinaryContent.Create(internalAssistantToolsFileSearchFileSearch, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalAssistantToolsFileSearchFileSearch(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantToolsFileSearchFileSearch(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.cs b/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.cs index 6da7606a9..993db5f2e 100644 --- a/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.cs +++ b/src/Generated/Models/InternalAssistantToolsFileSearchFileSearch.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal partial class InternalAssistantToolsFileSearchFileSearch { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalAssistantToolsFileSearchFileSearch() { } - internal InternalAssistantToolsFileSearchFileSearch(int? internalMaxNumResults, FileSearchRankingOptions rankingOptions, IDictionary serializedAdditionalRawData) + internal InternalAssistantToolsFileSearchFileSearch(FileSearchRankingOptions rankingOptions, int? internalMaxNumResults, IDictionary additionalBinaryDataProperties) { - InternalMaxNumResults = internalMaxNumResults; RankingOptions = rankingOptions; - SerializedAdditionalRawData = serializedAdditionalRawData; + InternalMaxNumResults = internalMaxNumResults; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public FileSearchRankingOptions RankingOptions { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.Serialization.cs b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.Serialization.cs index ef306bf2a..c73097323 100644 --- a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.Serialization.cs +++ b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ internal partial class InternalAssistantToolsFileSearchTypeOnly : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantToolsFileSearchTypeOnly)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter w } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +51,49 @@ void IJsonModel.Write(Utf8JsonWriter w #endif } } - writer.WriteEndObject(); } - InternalAssistantToolsFileSearchTypeOnly IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantToolsFileSearchTypeOnly IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalAssistantToolsFileSearchTypeOnly JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantToolsFileSearchTypeOnly)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantToolsFileSearchTypeOnly(document.RootElement, options); } - internal static InternalAssistantToolsFileSearchTypeOnly DeserializeInternalAssistantToolsFileSearchTypeOnly(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantToolsFileSearchTypeOnly DeserializeInternalAssistantToolsFileSearchTypeOnly(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalAssistantToolsFileSearchTypeOnlyType type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalAssistantToolsFileSearchTypeOnlyType @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalAssistantToolsFileSearchTypeOnlyType(property.Value.GetString()); + @type = new InternalAssistantToolsFileSearchTypeOnlyType(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantToolsFileSearchTypeOnly(type, serializedAdditionalRawData); + return new InternalAssistantToolsFileSearchTypeOnly(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +103,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalAssistantToolsFileSearchTypeOnly IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantToolsFileSearchTypeOnly IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalAssistantToolsFileSearchTypeOnly 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantToolsFileSearchTypeOnly(document.RootElement, options); } default: @@ -119,15 +122,20 @@ InternalAssistantToolsFileSearchTypeOnly IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalAssistantToolsFileSearchTypeOnly FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAssistantToolsFileSearchTypeOnly internalAssistantToolsFileSearchTypeOnly) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAssistantToolsFileSearchTypeOnly(document.RootElement); + if (internalAssistantToolsFileSearchTypeOnly == null) + { + return null; + } + return BinaryContent.Create(internalAssistantToolsFileSearchTypeOnly, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalAssistantToolsFileSearchTypeOnly(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantToolsFileSearchTypeOnly(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.cs b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.cs index 607f7fb44..1d969ec0b 100644 --- a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.cs +++ b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnly.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { internal partial class InternalAssistantToolsFileSearchTypeOnly { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalAssistantToolsFileSearchTypeOnly() { } - internal InternalAssistantToolsFileSearchTypeOnly(InternalAssistantToolsFileSearchTypeOnlyType type, IDictionary serializedAdditionalRawData) + internal InternalAssistantToolsFileSearchTypeOnly(InternalAssistantToolsFileSearchTypeOnlyType @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalAssistantToolsFileSearchTypeOnlyType Type { get; } = InternalAssistantToolsFileSearchTypeOnlyType.FileSearch; + public InternalAssistantToolsFileSearchTypeOnlyType Type { get; } = "file_search"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnlyType.cs b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnlyType.cs index c1378a9ae..3c6f5cfc2 100644 --- a/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnlyType.cs +++ b/src/Generated/Models/InternalAssistantToolsFileSearchTypeOnlyType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalAssistantToolsFileSearchTypeOnlyType : IEquatable { private readonly string _value; + private const string FileSearchValue = "file_search"; public InternalAssistantToolsFileSearchTypeOnlyType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FileSearchValue = "file_search"; + _value = value; + } public static InternalAssistantToolsFileSearchTypeOnlyType FileSearch { get; } = new InternalAssistantToolsFileSearchTypeOnlyType(FileSearchValue); + public static bool operator ==(InternalAssistantToolsFileSearchTypeOnlyType left, InternalAssistantToolsFileSearchTypeOnlyType right) => left.Equals(right); + public static bool operator !=(InternalAssistantToolsFileSearchTypeOnlyType left, InternalAssistantToolsFileSearchTypeOnlyType right) => !left.Equals(right); + public static implicit operator InternalAssistantToolsFileSearchTypeOnlyType(string value) => new InternalAssistantToolsFileSearchTypeOnlyType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalAssistantToolsFileSearchTypeOnlyType other && Equals(other); + public bool Equals(InternalAssistantToolsFileSearchTypeOnlyType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.Serialization.cs b/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.Serialization.cs index 0ef83db21..bd02f8444 100644 --- a/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.Serialization.cs +++ b/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalAssistantsNamedToolChoiceFunction : IJsonModel { + internal InternalAssistantsNamedToolChoiceFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAssistantsNamedToolChoiceFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalAssistantsNamedToolChoiceFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAssistantsNamedToolChoiceFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalAssistantsNamedToolChoiceFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAssistantsNamedToolChoiceFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAssistantsNamedToolChoiceFunction(document.RootElement, options); } - internal static InternalAssistantsNamedToolChoiceFunction DeserializeInternalAssistantsNamedToolChoiceFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAssistantsNamedToolChoiceFunction DeserializeInternalAssistantsNamedToolChoiceFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantsNamedToolChoiceFunction(name, serializedAdditionalRawData); + return new InternalAssistantsNamedToolChoiceFunction(name, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalAssistantsNamedToolChoiceFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAssistantsNamedToolChoiceFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalAssistantsNamedToolChoiceFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAssistantsNamedToolChoiceFunction(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalAssistantsNamedToolChoiceFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalAssistantsNamedToolChoiceFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAssistantsNamedToolChoiceFunction internalAssistantsNamedToolChoiceFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAssistantsNamedToolChoiceFunction(document.RootElement); + if (internalAssistantsNamedToolChoiceFunction == null) + { + return null; + } + return BinaryContent.Create(internalAssistantsNamedToolChoiceFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalAssistantsNamedToolChoiceFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAssistantsNamedToolChoiceFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.cs b/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.cs index 88e7c6d17..dc8a7c26a 100644 --- a/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.cs +++ b/src/Generated/Models/InternalAssistantsNamedToolChoiceFunction.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalAssistantsNamedToolChoiceFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalAssistantsNamedToolChoiceFunction(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,16 +19,18 @@ public InternalAssistantsNamedToolChoiceFunction(string name) Name = name; } - internal InternalAssistantsNamedToolChoiceFunction(string name, IDictionary serializedAdditionalRawData) + internal InternalAssistantsNamedToolChoiceFunction(string name, IDictionary additionalBinaryDataProperties) { Name = name; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalAssistantsNamedToolChoiceFunction() + public string Name { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; set; } } } diff --git a/src/Generated/Models/InternalAssistantsNamedToolChoiceType.cs b/src/Generated/Models/InternalAssistantsNamedToolChoiceType.cs index a71bdc9a0..c8eec5f29 100644 --- a/src/Generated/Models/InternalAssistantsNamedToolChoiceType.cs +++ b/src/Generated/Models/InternalAssistantsNamedToolChoiceType.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalAssistantsNamedToolChoiceType : IEquatable { private readonly string _value; + private const string FunctionValue = "function"; + private const string CodeInterpreterValue = "code_interpreter"; + private const string FileSearchValue = "file_search"; public InternalAssistantsNamedToolChoiceType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FunctionValue = "function"; - private const string CodeInterpreterValue = "code_interpreter"; - private const string FileSearchValue = "file_search"; + _value = value; + } public static InternalAssistantsNamedToolChoiceType Function { get; } = new InternalAssistantsNamedToolChoiceType(FunctionValue); + public static InternalAssistantsNamedToolChoiceType CodeInterpreter { get; } = new InternalAssistantsNamedToolChoiceType(CodeInterpreterValue); + public static InternalAssistantsNamedToolChoiceType FileSearch { get; } = new InternalAssistantsNamedToolChoiceType(FileSearchValue); + public static bool operator ==(InternalAssistantsNamedToolChoiceType left, InternalAssistantsNamedToolChoiceType right) => left.Equals(right); + public static bool operator !=(InternalAssistantsNamedToolChoiceType left, InternalAssistantsNamedToolChoiceType right) => !left.Equals(right); + public static implicit operator InternalAssistantsNamedToolChoiceType(string value) => new InternalAssistantsNamedToolChoiceType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalAssistantsNamedToolChoiceType other && Equals(other); + public bool Equals(InternalAssistantsNamedToolChoiceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalAutoChunkingStrategy.Serialization.cs b/src/Generated/Models/InternalAutoChunkingStrategy.Serialization.cs index 3f1028c9f..2c92732ee 100644 --- a/src/Generated/Models/InternalAutoChunkingStrategy.Serialization.cs +++ b/src/Generated/Models/InternalAutoChunkingStrategy.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,84 +15,62 @@ internal partial class InternalAutoChunkingStrategy : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAutoChunkingStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalAutoChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAutoChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAutoChunkingStrategy)JsonModelCreateCore(ref reader, options); + + protected override FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAutoChunkingStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAutoChunkingStrategy(document.RootElement, options); } - internal static InternalAutoChunkingStrategy DeserializeInternalAutoChunkingStrategy(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAutoChunkingStrategy DeserializeInternalAutoChunkingStrategy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "auto"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAutoChunkingStrategy(type, serializedAdditionalRawData); + return new InternalAutoChunkingStrategy(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalAutoChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAutoChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAutoChunkingStrategy)PersistableModelCreateCore(data, options); + protected override FileChunkingStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAutoChunkingStrategy(document.RootElement, options); } default: @@ -119,15 +99,20 @@ InternalAutoChunkingStrategy IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalAutoChunkingStrategy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAutoChunkingStrategy internalAutoChunkingStrategy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAutoChunkingStrategy(document.RootElement); + if (internalAutoChunkingStrategy == null) + { + return null; + } + return BinaryContent.Create(internalAutoChunkingStrategy, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalAutoChunkingStrategy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAutoChunkingStrategy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAutoChunkingStrategy.cs b/src/Generated/Models/InternalAutoChunkingStrategy.cs index 09a132829..0ff708766 100644 --- a/src/Generated/Models/InternalAutoChunkingStrategy.cs +++ b/src/Generated/Models/InternalAutoChunkingStrategy.cs @@ -9,12 +9,11 @@ namespace OpenAI.VectorStores { internal partial class InternalAutoChunkingStrategy : FileChunkingStrategy { - public InternalAutoChunkingStrategy() + public InternalAutoChunkingStrategy() : base("auto") { - Type = "auto"; } - internal InternalAutoChunkingStrategy(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalAutoChunkingStrategy(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.Serialization.cs b/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.Serialization.cs index ba2aafdaa..c258abd77 100644 --- a/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.Serialization.cs +++ b/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,84 +15,62 @@ internal partial class InternalAutoChunkingStrategyRequestParam : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalAutoChunkingStrategyRequestParam)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalAutoChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalAutoChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAutoChunkingStrategyRequestParam)JsonModelCreateCore(ref reader, options); + + protected override InternalFileChunkingStrategyRequestParam JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalAutoChunkingStrategyRequestParam)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalAutoChunkingStrategyRequestParam(document.RootElement, options); } - internal static InternalAutoChunkingStrategyRequestParam DeserializeInternalAutoChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalAutoChunkingStrategyRequestParam DeserializeInternalAutoChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "auto"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAutoChunkingStrategyRequestParam(type, serializedAdditionalRawData); + return new InternalAutoChunkingStrategyRequestParam(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalAutoChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalAutoChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAutoChunkingStrategyRequestParam)PersistableModelCreateCore(data, options); + protected override InternalFileChunkingStrategyRequestParam 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalAutoChunkingStrategyRequestParam(document.RootElement, options); } default: @@ -119,15 +99,20 @@ InternalAutoChunkingStrategyRequestParam IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalAutoChunkingStrategyRequestParam FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalAutoChunkingStrategyRequestParam internalAutoChunkingStrategyRequestParam) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAutoChunkingStrategyRequestParam(document.RootElement); + if (internalAutoChunkingStrategyRequestParam == null) + { + return null; + } + return BinaryContent.Create(internalAutoChunkingStrategyRequestParam, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalAutoChunkingStrategyRequestParam(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalAutoChunkingStrategyRequestParam(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.cs b/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.cs index 3b429d3e7..9fd245b0c 100644 --- a/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.cs +++ b/src/Generated/Models/InternalAutoChunkingStrategyRequestParam.cs @@ -9,12 +9,11 @@ namespace OpenAI.VectorStores { internal partial class InternalAutoChunkingStrategyRequestParam : InternalFileChunkingStrategyRequestParam { - public InternalAutoChunkingStrategyRequestParam() + public InternalAutoChunkingStrategyRequestParam() : base("auto") { - Type = "auto"; } - internal InternalAutoChunkingStrategyRequestParam(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalAutoChunkingStrategyRequestParam(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalBatchCompletionTimeframe.cs b/src/Generated/Models/InternalBatchCompletionTimeframe.cs index 836a9c1e7..b3a3eb0cd 100644 --- a/src/Generated/Models/InternalBatchCompletionTimeframe.cs +++ b/src/Generated/Models/InternalBatchCompletionTimeframe.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalBatchCompletionTimeframe : IEquatable { private readonly string _value; + private const string _24hValue = "24h"; public InternalBatchCompletionTimeframe(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string _24hValue = "24h"; + _value = value; + } public static InternalBatchCompletionTimeframe _24h { get; } = new InternalBatchCompletionTimeframe(_24hValue); + public static bool operator ==(InternalBatchCompletionTimeframe left, InternalBatchCompletionTimeframe right) => left.Equals(right); + public static bool operator !=(InternalBatchCompletionTimeframe left, InternalBatchCompletionTimeframe right) => !left.Equals(right); + public static implicit operator InternalBatchCompletionTimeframe(string value) => new InternalBatchCompletionTimeframe(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalBatchCompletionTimeframe other && Equals(other); + public bool Equals(InternalBatchCompletionTimeframe other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalBatchError.Serialization.cs b/src/Generated/Models/InternalBatchError.Serialization.cs index 0e768f6aa..c3d3f4c0d 100644 --- a/src/Generated/Models/InternalBatchError.Serialization.cs +++ b/src/Generated/Models/InternalBatchError.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,24 +15,29 @@ internal partial class InternalBatchError : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) + if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) + if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("param") != true && Optional.IsDefined(Param)) + if (Optional.IsDefined(Param) && _additionalBinaryDataProperties?.ContainsKey("param") != true) { if (Param != null) { @@ -40,10 +46,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("param"); + writer.WriteNull("param"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("line") != true && Optional.IsDefined(Line)) + if (Optional.IsDefined(Line) && _additionalBinaryDataProperties?.ContainsKey("line") != true) { if (Line != null) { @@ -52,12 +58,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("line"); + writer.WriteNull("line"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,81 +80,77 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - InternalBatchError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchError(document.RootElement, options); } - internal static InternalBatchError DeserializeInternalBatchError(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchError DeserializeInternalBatchError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string code = default; string message = default; - string param = default; + string @param = default; int? line = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("param"u8)) + if (prop.NameEquals("param"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - param = null; + @param = null; continue; } - param = property.Value.GetString(); + @param = prop.Value.GetString(); continue; } - if (property.NameEquals("line"u8)) + if (prop.NameEquals("line"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { line = null; continue; } - line = property.Value.GetInt32(); + line = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchError(code, message, param, line, serializedAdditionalRawData); + return new InternalBatchError(code, message, @param, line, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -158,15 +160,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - InternalBatchError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchError(document.RootElement, options); } default: @@ -176,15 +179,20 @@ InternalBatchError IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchError internalBatchError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchError(document.RootElement); + if (internalBatchError == null) + { + return null; + } + return BinaryContent.Create(internalBatchError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchError.cs b/src/Generated/Models/InternalBatchError.cs index 411b48c42..576ce6495 100644 --- a/src/Generated/Models/InternalBatchError.cs +++ b/src/Generated/Models/InternalBatchError.cs @@ -9,23 +9,33 @@ namespace OpenAI.Batch { internal partial class InternalBatchError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchError() { } - internal InternalBatchError(string code, string message, string param, int? line, IDictionary serializedAdditionalRawData) + internal InternalBatchError(string code, string message, string @param, int? line, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - Param = param; + Param = @param; Line = line; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Code { get; } + public string Message { get; } + public string Param { get; } + public int? Line { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchErrors.Serialization.cs b/src/Generated/Models/InternalBatchErrors.Serialization.cs index d75c78a08..7d09b6dca 100644 --- a/src/Generated/Models/InternalBatchErrors.Serialization.cs +++ b/src/Generated/Models/InternalBatchErrors.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,31 +15,36 @@ internal partial class InternalBatchErrors : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchErrors)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true && Optional.IsDefined(Object)) + if (Optional.IsDefined(Object) && _additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true && Optional.IsCollectionDefined(Data)) + if (Optional.IsCollectionDefined(Data) && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (InternalBatchError item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,52 +61,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri #endif } } - writer.WriteEndObject(); } - InternalBatchErrors IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchErrors IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchErrors JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchErrors)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchErrors(document.RootElement, options); } - internal static InternalBatchErrors DeserializeInternalBatchErrors(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchErrors DeserializeInternalBatchErrors(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalBatchErrorsObject? @object = default; - IReadOnlyList data = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList data = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - @object = new InternalBatchErrorsObject(property.Value.GetString()); + @object = new InternalBatchErrorsObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalBatchError.DeserializeInternalBatchError(item, options)); } @@ -109,18 +112,17 @@ internal static InternalBatchErrors DeserializeInternalBatchErrors(JsonElement e } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchErrors(@object, data ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalBatchErrors(@object, data ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -130,15 +132,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - InternalBatchErrors IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchErrors IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchErrors 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchErrors(document.RootElement, options); } default: @@ -148,15 +151,20 @@ InternalBatchErrors IPersistableModel.Create(BinaryData dat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchErrors FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchErrors internalBatchErrors) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchErrors(document.RootElement); + if (internalBatchErrors == null) + { + return null; + } + return BinaryContent.Create(internalBatchErrors, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchErrors(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchErrors(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchErrors.cs b/src/Generated/Models/InternalBatchErrors.cs index ef20e9e07..49098797b 100644 --- a/src/Generated/Models/InternalBatchErrors.cs +++ b/src/Generated/Models/InternalBatchErrors.cs @@ -4,25 +4,34 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalBatchErrors { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchErrors() { Data = new ChangeTrackingList(); } - internal InternalBatchErrors(InternalBatchErrorsObject? @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + internal InternalBatchErrors(InternalBatchErrorsObject? @object, IList data, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalBatchErrorsObject? Object { get; } - public IReadOnlyList Data { get; } + + public IList Data { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchErrorsObject.cs b/src/Generated/Models/InternalBatchErrorsObject.cs index 0f98bd40d..ee716ad76 100644 --- a/src/Generated/Models/InternalBatchErrorsObject.cs +++ b/src/Generated/Models/InternalBatchErrorsObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalBatchErrorsObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalBatchErrorsObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalBatchErrorsObject List { get; } = new InternalBatchErrorsObject(ListValue); + public static bool operator ==(InternalBatchErrorsObject left, InternalBatchErrorsObject right) => left.Equals(right); + public static bool operator !=(InternalBatchErrorsObject left, InternalBatchErrorsObject right) => !left.Equals(right); + public static implicit operator InternalBatchErrorsObject(string value) => new InternalBatchErrorsObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalBatchErrorsObject other && Equals(other); + public bool Equals(InternalBatchErrorsObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalBatchJob.Serialization.cs b/src/Generated/Models/InternalBatchJob.Serialization.cs index f0aa4f8f6..ee8c9a1b2 100644 --- a/src/Generated/Models/InternalBatchJob.Serialization.cs +++ b/src/Generated/Models/InternalBatchJob.Serialization.cs @@ -7,116 +7,126 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalBatchJob : IJsonModel { + internal InternalBatchJob() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchJob)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) + if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) { writer.WritePropertyName("endpoint"u8); writer.WriteStringValue(Endpoint); } - if (SerializedAdditionalRawData?.ContainsKey("errors") != true && Optional.IsDefined(Errors)) + if (Optional.IsDefined(Errors) && _additionalBinaryDataProperties?.ContainsKey("errors") != true) { writer.WritePropertyName("errors"u8); writer.WriteObjectValue(Errors, options); } - if (SerializedAdditionalRawData?.ContainsKey("input_file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_file_id") != true) { writer.WritePropertyName("input_file_id"u8); writer.WriteStringValue(InputFileId); } - if (SerializedAdditionalRawData?.ContainsKey("completion_window") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_window") != true) { writer.WritePropertyName("completion_window"u8); writer.WriteStringValue(CompletionWindow); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("output_file_id") != true && Optional.IsDefined(OutputFileId)) + if (Optional.IsDefined(OutputFileId) && _additionalBinaryDataProperties?.ContainsKey("output_file_id") != true) { writer.WritePropertyName("output_file_id"u8); writer.WriteStringValue(OutputFileId); } - if (SerializedAdditionalRawData?.ContainsKey("error_file_id") != true && Optional.IsDefined(ErrorFileId)) + if (Optional.IsDefined(ErrorFileId) && _additionalBinaryDataProperties?.ContainsKey("error_file_id") != true) { writer.WritePropertyName("error_file_id"u8); writer.WriteStringValue(ErrorFileId); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("in_progress_at") != true && Optional.IsDefined(InProgressAt)) + if (Optional.IsDefined(InProgressAt) && _additionalBinaryDataProperties?.ContainsKey("in_progress_at") != true) { writer.WritePropertyName("in_progress_at"u8); writer.WriteNumberValue(InProgressAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("expires_at") != true && Optional.IsDefined(ExpiresAt)) + if (Optional.IsDefined(ExpiresAt) && _additionalBinaryDataProperties?.ContainsKey("expires_at") != true) { writer.WritePropertyName("expires_at"u8); writer.WriteNumberValue(ExpiresAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("finalizing_at") != true && Optional.IsDefined(FinalizingAt)) + if (Optional.IsDefined(FinalizingAt) && _additionalBinaryDataProperties?.ContainsKey("finalizing_at") != true) { writer.WritePropertyName("finalizing_at"u8); writer.WriteNumberValue(FinalizingAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("completed_at") != true && Optional.IsDefined(CompletedAt)) + if (Optional.IsDefined(CompletedAt) && _additionalBinaryDataProperties?.ContainsKey("completed_at") != true) { writer.WritePropertyName("completed_at"u8); writer.WriteNumberValue(CompletedAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("failed_at") != true && Optional.IsDefined(FailedAt)) + if (Optional.IsDefined(FailedAt) && _additionalBinaryDataProperties?.ContainsKey("failed_at") != true) { writer.WritePropertyName("failed_at"u8); writer.WriteNumberValue(FailedAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("expired_at") != true && Optional.IsDefined(ExpiredAt)) + if (Optional.IsDefined(ExpiredAt) && _additionalBinaryDataProperties?.ContainsKey("expired_at") != true) { writer.WritePropertyName("expired_at"u8); writer.WriteNumberValue(ExpiredAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("cancelling_at") != true && Optional.IsDefined(CancellingAt)) + if (Optional.IsDefined(CancellingAt) && _additionalBinaryDataProperties?.ContainsKey("cancelling_at") != true) { writer.WritePropertyName("cancelling_at"u8); writer.WriteNumberValue(CancellingAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("cancelled_at") != true && Optional.IsDefined(CancelledAt)) + if (Optional.IsDefined(CancelledAt) && _additionalBinaryDataProperties?.ContainsKey("cancelled_at") != true) { writer.WritePropertyName("cancelled_at"u8); writer.WriteNumberValue(CancelledAt.Value, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("request_counts") != true && Optional.IsDefined(RequestCounts)) + if (Optional.IsDefined(RequestCounts) && _additionalBinaryDataProperties?.ContainsKey("request_counts") != true) { writer.WritePropertyName("request_counts"u8); writer.WriteObjectValue(RequestCounts, options); } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -125,18 +135,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -144,7 +159,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -153,25 +168,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter #endif } } - writer.WriteEndObject(); } - InternalBatchJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchJob JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchJob)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchJob(document.RootElement, options); } - internal static InternalBatchJob DeserializeInternalBatchJob(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchJob DeserializeInternalBatchJob(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -195,167 +208,171 @@ internal static InternalBatchJob DeserializeInternalBatchJob(JsonElement element DateTimeOffset? cancellingAt = default; DateTimeOffset? cancelledAt = default; InternalBatchRequestCounts requestCounts = default; - IReadOnlyDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary metadata = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalBatchObject(property.Value.GetString()); + @object = new InternalBatchObject(prop.Value.GetString()); continue; } - if (property.NameEquals("endpoint"u8)) + if (prop.NameEquals("endpoint"u8)) { - endpoint = property.Value.GetString(); + endpoint = prop.Value.GetString(); continue; } - if (property.NameEquals("errors"u8)) + if (prop.NameEquals("errors"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - errors = InternalBatchErrors.DeserializeInternalBatchErrors(property.Value, options); + errors = InternalBatchErrors.DeserializeInternalBatchErrors(prop.Value, options); continue; } - if (property.NameEquals("input_file_id"u8)) + if (prop.NameEquals("input_file_id"u8)) { - inputFileId = property.Value.GetString(); + inputFileId = prop.Value.GetString(); continue; } - if (property.NameEquals("completion_window"u8)) + if (prop.NameEquals("completion_window"u8)) { - completionWindow = property.Value.GetString(); + completionWindow = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new InternalBatchStatus(property.Value.GetString()); + status = new InternalBatchStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("output_file_id"u8)) + if (prop.NameEquals("output_file_id"u8)) { - outputFileId = property.Value.GetString(); + outputFileId = prop.Value.GetString(); continue; } - if (property.NameEquals("error_file_id"u8)) + if (prop.NameEquals("error_file_id"u8)) { - errorFileId = property.Value.GetString(); + errorFileId = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("in_progress_at"u8)) + if (prop.NameEquals("in_progress_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - inProgressAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + inProgressAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("expires_at"u8)) + if (prop.NameEquals("expires_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("finalizing_at"u8)) + if (prop.NameEquals("finalizing_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - finalizingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + finalizingAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("completed_at"u8)) + if (prop.NameEquals("completed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("failed_at"u8)) + if (prop.NameEquals("failed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - failedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + failedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("expired_at"u8)) + if (prop.NameEquals("expired_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - expiredAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiredAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("cancelling_at"u8)) + if (prop.NameEquals("cancelling_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - cancellingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + cancellingAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("cancelled_at"u8)) + if (prop.NameEquals("cancelled_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - cancelledAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + cancelledAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("request_counts"u8)) + if (prop.NameEquals("request_counts"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - requestCounts = InternalBatchRequestCounts.DeserializeInternalBatchRequestCounts(property.Value, options); + requestCounts = InternalBatchRequestCounts.DeserializeInternalBatchRequestCounts(prop.Value, options); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalBatchJob( id, @object, @@ -377,13 +394,14 @@ internal static InternalBatchJob DeserializeInternalBatchJob(JsonElement element cancelledAt, requestCounts, metadata ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -393,15 +411,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - InternalBatchJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchJob 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchJob(document.RootElement, options); } default: @@ -411,15 +430,20 @@ InternalBatchJob IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchJob FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchJob internalBatchJob) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchJob(document.RootElement); + if (internalBatchJob == null) + { + return null; + } + return BinaryContent.Create(internalBatchJob, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchJob(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchJob(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchJob.cs b/src/Generated/Models/InternalBatchJob.cs index bbd35aeac..0654bf9a2 100644 --- a/src/Generated/Models/InternalBatchJob.cs +++ b/src/Generated/Models/InternalBatchJob.cs @@ -4,19 +4,16 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalBatchJob { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchJob(string id, string endpoint, string inputFileId, string completionWindow, InternalBatchStatus status, DateTimeOffset createdAt) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(inputFileId, nameof(inputFileId)); - Argument.AssertNotNull(completionWindow, nameof(completionWindow)); - Id = id; Endpoint = endpoint; InputFileId = inputFileId; @@ -26,7 +23,7 @@ internal InternalBatchJob(string id, string endpoint, string inputFileId, string Metadata = new ChangeTrackingDictionary(); } - internal InternalBatchJob(string id, InternalBatchObject @object, string endpoint, InternalBatchErrors errors, string inputFileId, string completionWindow, InternalBatchStatus status, string outputFileId, string errorFileId, DateTimeOffset createdAt, DateTimeOffset? inProgressAt, DateTimeOffset? expiresAt, DateTimeOffset? finalizingAt, DateTimeOffset? completedAt, DateTimeOffset? failedAt, DateTimeOffset? expiredAt, DateTimeOffset? cancellingAt, DateTimeOffset? cancelledAt, InternalBatchRequestCounts requestCounts, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal InternalBatchJob(string id, InternalBatchObject @object, string endpoint, InternalBatchErrors errors, string inputFileId, string completionWindow, InternalBatchStatus status, string outputFileId, string errorFileId, DateTimeOffset createdAt, DateTimeOffset? inProgressAt, DateTimeOffset? expiresAt, DateTimeOffset? finalizingAt, DateTimeOffset? completedAt, DateTimeOffset? failedAt, DateTimeOffset? expiredAt, DateTimeOffset? cancellingAt, DateTimeOffset? cancelledAt, InternalBatchRequestCounts requestCounts, IDictionary metadata, IDictionary additionalBinaryDataProperties) { Id = id; Object = @object; @@ -48,33 +45,53 @@ internal InternalBatchJob(string id, InternalBatchObject @object, string endpoin CancelledAt = cancelledAt; RequestCounts = requestCounts; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalBatchJob() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } - public InternalBatchObject Object { get; } = InternalBatchObject.Batch; + + public InternalBatchObject Object { get; } = "batch"; public string Endpoint { get; } + public InternalBatchErrors Errors { get; } + public string InputFileId { get; } + public string CompletionWindow { get; } + public InternalBatchStatus Status { get; } + public string OutputFileId { get; } + public string ErrorFileId { get; } + public DateTimeOffset CreatedAt { get; } + public DateTimeOffset? InProgressAt { get; } + public DateTimeOffset? ExpiresAt { get; } + public DateTimeOffset? FinalizingAt { get; } + public DateTimeOffset? CompletedAt { get; } + public DateTimeOffset? FailedAt { get; } + public DateTimeOffset? ExpiredAt { get; } + public DateTimeOffset? CancellingAt { get; } + public DateTimeOffset? CancelledAt { get; } + public InternalBatchRequestCounts RequestCounts { get; } - public IReadOnlyDictionary Metadata { get; } + + public IDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchObject.cs b/src/Generated/Models/InternalBatchObject.cs index 96ff270ec..c1d37dbda 100644 --- a/src/Generated/Models/InternalBatchObject.cs +++ b/src/Generated/Models/InternalBatchObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalBatchObject : IEquatable { private readonly string _value; + private const string BatchValue = "batch"; public InternalBatchObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string BatchValue = "batch"; + _value = value; + } public static InternalBatchObject Batch { get; } = new InternalBatchObject(BatchValue); + public static bool operator ==(InternalBatchObject left, InternalBatchObject right) => left.Equals(right); + public static bool operator !=(InternalBatchObject left, InternalBatchObject right) => !left.Equals(right); + public static implicit operator InternalBatchObject(string value) => new InternalBatchObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalBatchObject other && Equals(other); + public bool Equals(InternalBatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalBatchRequestCounts.Serialization.cs b/src/Generated/Models/InternalBatchRequestCounts.Serialization.cs index ad7ad277b..e1af9a276 100644 --- a/src/Generated/Models/InternalBatchRequestCounts.Serialization.cs +++ b/src/Generated/Models/InternalBatchRequestCounts.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalBatchRequestCounts : IJsonModel { + internal InternalBatchRequestCounts() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchRequestCounts)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("total") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total") != true) { writer.WritePropertyName("total"u8); writer.WriteNumberValue(Total); } - if (SerializedAdditionalRawData?.ContainsKey("completed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed") != true) { writer.WritePropertyName("completed"u8); writer.WriteNumberValue(Completed); } - if (SerializedAdditionalRawData?.ContainsKey("failed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("failed") != true) { writer.WritePropertyName("failed"u8); writer.WriteNumberValue(Failed); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,25 +65,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - InternalBatchRequestCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchRequestCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchRequestCounts JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchRequestCounts)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchRequestCounts(document.RootElement, options); } - internal static InternalBatchRequestCounts DeserializeInternalBatchRequestCounts(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchRequestCounts DeserializeInternalBatchRequestCounts(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -81,39 +89,37 @@ internal static InternalBatchRequestCounts DeserializeInternalBatchRequestCounts int total = default; int completed = default; int failed = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("total"u8)) + if (prop.NameEquals("total"u8)) { - total = property.Value.GetInt32(); + total = prop.Value.GetInt32(); continue; } - if (property.NameEquals("completed"u8)) + if (prop.NameEquals("completed"u8)) { - completed = property.Value.GetInt32(); + completed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("failed"u8)) + if (prop.NameEquals("failed"u8)) { - failed = property.Value.GetInt32(); + failed = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchRequestCounts(total, completed, failed, serializedAdditionalRawData); + return new InternalBatchRequestCounts(total, completed, failed, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalBatchRequestCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchRequestCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchRequestCounts 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchRequestCounts(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalBatchRequestCounts IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchRequestCounts FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchRequestCounts internalBatchRequestCounts) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchRequestCounts(document.RootElement); + if (internalBatchRequestCounts == null) + { + return null; + } + return BinaryContent.Create(internalBatchRequestCounts, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchRequestCounts(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchRequestCounts(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchRequestCounts.cs b/src/Generated/Models/InternalBatchRequestCounts.cs index 1e9731e07..a041be13d 100644 --- a/src/Generated/Models/InternalBatchRequestCounts.cs +++ b/src/Generated/Models/InternalBatchRequestCounts.cs @@ -9,7 +9,8 @@ namespace OpenAI.Batch { internal partial class InternalBatchRequestCounts { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchRequestCounts(int total, int completed, int failed) { Total = total; @@ -17,20 +18,24 @@ internal InternalBatchRequestCounts(int total, int completed, int failed) Failed = failed; } - internal InternalBatchRequestCounts(int total, int completed, int failed, IDictionary serializedAdditionalRawData) + internal InternalBatchRequestCounts(int total, int completed, int failed, IDictionary additionalBinaryDataProperties) { Total = total; Completed = completed; Failed = failed; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalBatchRequestCounts() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int Total { get; } + public int Completed { get; } + public int Failed { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchRequestInput.Serialization.cs b/src/Generated/Models/InternalBatchRequestInput.Serialization.cs index fe753aed3..103045cb5 100644 --- a/src/Generated/Models/InternalBatchRequestInput.Serialization.cs +++ b/src/Generated/Models/InternalBatchRequestInput.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,31 +15,36 @@ internal partial class InternalBatchRequestInput : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchRequestInput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("custom_id") != true && Optional.IsDefined(CustomId)) + if (Optional.IsDefined(CustomId) && _additionalBinaryDataProperties?.ContainsKey("custom_id") != true) { writer.WritePropertyName("custom_id"u8); writer.WriteStringValue(CustomId); } - if (SerializedAdditionalRawData?.ContainsKey("method") != true && Optional.IsDefined(Method)) + if (Optional.IsDefined(Method) && _additionalBinaryDataProperties?.ContainsKey("method") != true) { writer.WritePropertyName("method"u8); writer.WriteStringValue(Method.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("url") != true && Optional.IsDefined(Url)) + if (Optional.IsDefined(Url) && _additionalBinaryDataProperties?.ContainsKey("url") != true) { writer.WritePropertyName("url"u8); writer.WriteStringValue(Url.AbsoluteUri); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,73 +61,69 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - InternalBatchRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchRequestInput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchRequestInput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchRequestInput(document.RootElement, options); } - internal static InternalBatchRequestInput DeserializeInternalBatchRequestInput(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchRequestInput DeserializeInternalBatchRequestInput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string customId = default; - InternalBatchRequestInputMethod? method = default; + InternalBatchRequestInputMethod? @method = default; Uri url = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("custom_id"u8)) + if (prop.NameEquals("custom_id"u8)) { - customId = property.Value.GetString(); + customId = prop.Value.GetString(); continue; } - if (property.NameEquals("method"u8)) + if (prop.NameEquals("method"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - method = new InternalBatchRequestInputMethod(property.Value.GetString()); + @method = new InternalBatchRequestInputMethod(prop.Value.GetString()); continue; } - if (property.NameEquals("url"u8)) + if (prop.NameEquals("url"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - url = new Uri(property.Value.GetString()); + url = new Uri(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchRequestInput(customId, method, url, serializedAdditionalRawData); + return new InternalBatchRequestInput(customId, @method, url, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -131,15 +133,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - InternalBatchRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchRequestInput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchRequestInput(document.RootElement, options); } default: @@ -149,15 +152,20 @@ InternalBatchRequestInput IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchRequestInput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchRequestInput internalBatchRequestInput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchRequestInput(document.RootElement); + if (internalBatchRequestInput == null) + { + return null; + } + return BinaryContent.Create(internalBatchRequestInput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchRequestInput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchRequestInput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchRequestInput.cs b/src/Generated/Models/InternalBatchRequestInput.cs index 7e4b58c93..73e2768f9 100644 --- a/src/Generated/Models/InternalBatchRequestInput.cs +++ b/src/Generated/Models/InternalBatchRequestInput.cs @@ -9,21 +9,30 @@ namespace OpenAI.Batch { internal partial class InternalBatchRequestInput { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalBatchRequestInput() { } - internal InternalBatchRequestInput(string customId, InternalBatchRequestInputMethod? method, Uri url, IDictionary serializedAdditionalRawData) + internal InternalBatchRequestInput(string customId, InternalBatchRequestInputMethod? @method, Uri url, IDictionary additionalBinaryDataProperties) { CustomId = customId; - Method = method; + Method = @method; Url = url; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string CustomId { get; set; } + public InternalBatchRequestInputMethod? Method { get; set; } + public Uri Url { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchRequestInputMethod.cs b/src/Generated/Models/InternalBatchRequestInputMethod.cs index daff5451d..8e1e03a89 100644 --- a/src/Generated/Models/InternalBatchRequestInputMethod.cs +++ b/src/Generated/Models/InternalBatchRequestInputMethod.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalBatchRequestInputMethod : IEquatable { private readonly string _value; + private const string POSTValue = "POST"; public InternalBatchRequestInputMethod(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string POSTValue = "POST"; + _value = value; + } public static InternalBatchRequestInputMethod POST { get; } = new InternalBatchRequestInputMethod(POSTValue); + public static bool operator ==(InternalBatchRequestInputMethod left, InternalBatchRequestInputMethod right) => left.Equals(right); + public static bool operator !=(InternalBatchRequestInputMethod left, InternalBatchRequestInputMethod right) => !left.Equals(right); + public static implicit operator InternalBatchRequestInputMethod(string value) => new InternalBatchRequestInputMethod(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalBatchRequestInputMethod other && Equals(other); + public bool Equals(InternalBatchRequestInputMethod other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalBatchRequestOutput.Serialization.cs b/src/Generated/Models/InternalBatchRequestOutput.Serialization.cs index cd87dfd3b..e2f37f4af 100644 --- a/src/Generated/Models/InternalBatchRequestOutput.Serialization.cs +++ b/src/Generated/Models/InternalBatchRequestOutput.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,24 +15,29 @@ internal partial class InternalBatchRequestOutput : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchRequestOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("custom_id") != true && Optional.IsDefined(CustomId)) + if (Optional.IsDefined(CustomId) && _additionalBinaryDataProperties?.ContainsKey("custom_id") != true) { writer.WritePropertyName("custom_id"u8); writer.WriteStringValue(CustomId); } - if (SerializedAdditionalRawData?.ContainsKey("response") != true && Optional.IsDefined(Response)) + if (Optional.IsDefined(Response) && _additionalBinaryDataProperties?.ContainsKey("response") != true) { if (Response != null) { @@ -40,10 +46,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } else { - writer.WriteNull("response"); + writer.WriteNull("response"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("error") != true && Optional.IsDefined(Error)) + if (Optional.IsDefined(Error) && _additionalBinaryDataProperties?.ContainsKey("error") != true) { if (Error != null) { @@ -52,12 +58,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } else { - writer.WriteNull("error"); + writer.WriteNull("error"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - InternalBatchRequestOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchRequestOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchRequestOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchRequestOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchRequestOutput(document.RootElement, options); } - internal static InternalBatchRequestOutput DeserializeInternalBatchRequestOutput(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchRequestOutput DeserializeInternalBatchRequestOutput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -101,54 +105,52 @@ internal static InternalBatchRequestOutput DeserializeInternalBatchRequestOutput string customId = default; InternalBatchRequestOutputResponse response = default; InternalBatchRequestOutputError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("custom_id"u8)) + if (prop.NameEquals("custom_id"u8)) { - customId = property.Value.GetString(); + customId = prop.Value.GetString(); continue; } - if (property.NameEquals("response"u8)) + if (prop.NameEquals("response"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { response = null; continue; } - response = InternalBatchRequestOutputResponse.DeserializeInternalBatchRequestOutputResponse(property.Value, options); + response = InternalBatchRequestOutputResponse.DeserializeInternalBatchRequestOutputResponse(prop.Value, options); continue; } - if (property.NameEquals("error"u8)) + if (prop.NameEquals("error"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { error = null; continue; } - error = InternalBatchRequestOutputError.DeserializeInternalBatchRequestOutputError(property.Value, options); + error = InternalBatchRequestOutputError.DeserializeInternalBatchRequestOutputError(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchRequestOutput(id, customId, response, error, serializedAdditionalRawData); + return new InternalBatchRequestOutput(id, customId, response, error, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -158,15 +160,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalBatchRequestOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchRequestOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchRequestOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchRequestOutput(document.RootElement, options); } default: @@ -176,15 +179,20 @@ InternalBatchRequestOutput IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchRequestOutput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchRequestOutput internalBatchRequestOutput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchRequestOutput(document.RootElement); + if (internalBatchRequestOutput == null) + { + return null; + } + return BinaryContent.Create(internalBatchRequestOutput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchRequestOutput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchRequestOutput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchRequestOutput.cs b/src/Generated/Models/InternalBatchRequestOutput.cs index ae119ecd7..a277639b4 100644 --- a/src/Generated/Models/InternalBatchRequestOutput.cs +++ b/src/Generated/Models/InternalBatchRequestOutput.cs @@ -9,23 +9,33 @@ namespace OpenAI.Batch { internal partial class InternalBatchRequestOutput { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchRequestOutput() { } - internal InternalBatchRequestOutput(string id, string customId, InternalBatchRequestOutputResponse response, InternalBatchRequestOutputError error, IDictionary serializedAdditionalRawData) + internal InternalBatchRequestOutput(string id, string customId, InternalBatchRequestOutputResponse response, InternalBatchRequestOutputError error, IDictionary additionalBinaryDataProperties) { Id = id; CustomId = customId; Response = response; Error = error; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public string CustomId { get; } + public InternalBatchRequestOutputResponse Response { get; } + public InternalBatchRequestOutputError Error { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchRequestOutputError.Serialization.cs b/src/Generated/Models/InternalBatchRequestOutputError.Serialization.cs index 00f747f15..a8c726285 100644 --- a/src/Generated/Models/InternalBatchRequestOutputError.Serialization.cs +++ b/src/Generated/Models/InternalBatchRequestOutputError.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,26 +15,31 @@ internal partial class InternalBatchRequestOutputError : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchRequestOutputError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) + if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) + if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalBatchRequestOutputError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchRequestOutputError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchRequestOutputError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchRequestOutputError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchRequestOutputError(document.RootElement, options); } - internal static InternalBatchRequestOutputError DeserializeInternalBatchRequestOutputError(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchRequestOutputError DeserializeInternalBatchRequestOutputError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string code = default; string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchRequestOutputError(code, message, serializedAdditionalRawData); + return new InternalBatchRequestOutputError(code, message, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalBatchRequestOutputError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchRequestOutputError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchRequestOutputError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchRequestOutputError(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalBatchRequestOutputError IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchRequestOutputError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchRequestOutputError internalBatchRequestOutputError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchRequestOutputError(document.RootElement); + if (internalBatchRequestOutputError == null) + { + return null; + } + return BinaryContent.Create(internalBatchRequestOutputError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchRequestOutputError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchRequestOutputError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchRequestOutputError.cs b/src/Generated/Models/InternalBatchRequestOutputError.cs index b2ddd5bea..72e206cba 100644 --- a/src/Generated/Models/InternalBatchRequestOutputError.cs +++ b/src/Generated/Models/InternalBatchRequestOutputError.cs @@ -9,19 +9,27 @@ namespace OpenAI.Batch { internal partial class InternalBatchRequestOutputError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchRequestOutputError() { } - internal InternalBatchRequestOutputError(string code, string message, IDictionary serializedAdditionalRawData) + internal InternalBatchRequestOutputError(string code, string message, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Code { get; } + public string Message { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchRequestOutputResponse.Serialization.cs b/src/Generated/Models/InternalBatchRequestOutputResponse.Serialization.cs index 5f48d8090..435633b71 100644 --- a/src/Generated/Models/InternalBatchRequestOutputResponse.Serialization.cs +++ b/src/Generated/Models/InternalBatchRequestOutputResponse.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { @@ -14,24 +15,29 @@ internal partial class InternalBatchRequestOutputResponse : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalBatchRequestOutputResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("status_code") != true && Optional.IsDefined(StatusCode)) + if (Optional.IsDefined(StatusCode) && _additionalBinaryDataProperties?.ContainsKey("status_code") != true) { writer.WritePropertyName("status_code"u8); writer.WriteNumberValue(StatusCode.Value); } - if (SerializedAdditionalRawData?.ContainsKey("request_id") != true && Optional.IsDefined(RequestId)) + if (Optional.IsDefined(RequestId) && _additionalBinaryDataProperties?.ContainsKey("request_id") != true) { writer.WritePropertyName("request_id"u8); writer.WriteStringValue(RequestId); } - if (SerializedAdditionalRawData?.ContainsKey("body") != true && Optional.IsCollectionDefined(Body)) + if (Optional.IsCollectionDefined(Body) && _additionalBinaryDataProperties?.ContainsKey("body") != true) { writer.WritePropertyName("body"u8); writer.WriteStartObject(); @@ -44,7 +50,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, continue; } #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -54,9 +60,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WriteEndObject(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -64,7 +70,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -73,66 +79,63 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - InternalBatchRequestOutputResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalBatchRequestOutputResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalBatchRequestOutputResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalBatchRequestOutputResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalBatchRequestOutputResponse(document.RootElement, options); } - internal static InternalBatchRequestOutputResponse DeserializeInternalBatchRequestOutputResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalBatchRequestOutputResponse DeserializeInternalBatchRequestOutputResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } int? statusCode = default; string requestId = default; - IReadOnlyDictionary body = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary body = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("status_code"u8)) + if (prop.NameEquals("status_code"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - statusCode = property.Value.GetInt32(); + statusCode = prop.Value.GetInt32(); continue; } - if (property.NameEquals("request_id"u8)) + if (prop.NameEquals("request_id"u8)) { - requestId = property.Value.GetString(); + requestId = prop.Value.GetString(); continue; } - if (property.NameEquals("body"u8)) + if (prop.NameEquals("body"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - if (property0.Value.ValueKind == JsonValueKind.Null) + if (prop0.Value.ValueKind == JsonValueKind.Null) { - dictionary.Add(property0.Name, null); + dictionary.Add(prop0.Name, null); } else { - dictionary.Add(property0.Name, BinaryData.FromString(property0.Value.GetRawText())); + dictionary.Add(prop0.Name, BinaryData.FromString(prop0.Value.GetRawText())); } } body = dictionary; @@ -140,18 +143,17 @@ internal static InternalBatchRequestOutputResponse DeserializeInternalBatchReque } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalBatchRequestOutputResponse(statusCode, requestId, body ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new InternalBatchRequestOutputResponse(statusCode, requestId, body ?? new ChangeTrackingDictionary(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +163,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - InternalBatchRequestOutputResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalBatchRequestOutputResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalBatchRequestOutputResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalBatchRequestOutputResponse(document.RootElement, options); } default: @@ -179,15 +182,20 @@ InternalBatchRequestOutputResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalBatchRequestOutputResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalBatchRequestOutputResponse internalBatchRequestOutputResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalBatchRequestOutputResponse(document.RootElement); + if (internalBatchRequestOutputResponse == null) + { + return null; + } + return BinaryContent.Create(internalBatchRequestOutputResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalBatchRequestOutputResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalBatchRequestOutputResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalBatchRequestOutputResponse.cs b/src/Generated/Models/InternalBatchRequestOutputResponse.cs index 8435f20dc..b1866554e 100644 --- a/src/Generated/Models/InternalBatchRequestOutputResponse.cs +++ b/src/Generated/Models/InternalBatchRequestOutputResponse.cs @@ -4,27 +4,37 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalBatchRequestOutputResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalBatchRequestOutputResponse() { Body = new ChangeTrackingDictionary(); } - internal InternalBatchRequestOutputResponse(int? statusCode, string requestId, IReadOnlyDictionary body, IDictionary serializedAdditionalRawData) + internal InternalBatchRequestOutputResponse(int? statusCode, string requestId, IDictionary body, IDictionary additionalBinaryDataProperties) { StatusCode = statusCode; RequestId = requestId; Body = body; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int? StatusCode { get; } + public string RequestId { get; } - public IReadOnlyDictionary Body { get; } + + public IDictionary Body { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalBatchStatus.cs b/src/Generated/Models/InternalBatchStatus.cs index b34fe0bf8..33c7f6439 100644 --- a/src/Generated/Models/InternalBatchStatus.cs +++ b/src/Generated/Models/InternalBatchStatus.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalBatchStatus : IEquatable { private readonly string _value; - - public InternalBatchStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string ValidatingValue = "validating"; private const string FailedValue = "failed"; private const string InProgressValue = "in_progress"; @@ -25,24 +20,43 @@ public InternalBatchStatus(string value) private const string CancellingValue = "cancelling"; private const string CancelledValue = "cancelled"; + public InternalBatchStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalBatchStatus Validating { get; } = new InternalBatchStatus(ValidatingValue); + public static InternalBatchStatus Failed { get; } = new InternalBatchStatus(FailedValue); + public static InternalBatchStatus InProgress { get; } = new InternalBatchStatus(InProgressValue); + public static InternalBatchStatus Finalizing { get; } = new InternalBatchStatus(FinalizingValue); + public static InternalBatchStatus Completed { get; } = new InternalBatchStatus(CompletedValue); + public static InternalBatchStatus Expired { get; } = new InternalBatchStatus(ExpiredValue); + public static InternalBatchStatus Cancelling { get; } = new InternalBatchStatus(CancellingValue); + public static InternalBatchStatus Cancelled { get; } = new InternalBatchStatus(CancelledValue); + public static bool operator ==(InternalBatchStatus left, InternalBatchStatus right) => left.Equals(right); + public static bool operator !=(InternalBatchStatus left, InternalBatchStatus right) => !left.Equals(right); + public static implicit operator InternalBatchStatus(string value) => new InternalBatchStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalBatchStatus other && Equals(other); + public bool Equals(InternalBatchStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionFunctionCallOption.Serialization.cs b/src/Generated/Models/InternalChatCompletionFunctionCallOption.Serialization.cs index b8f419482..c43769045 100644 --- a/src/Generated/Models/InternalChatCompletionFunctionCallOption.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionFunctionCallOption.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionFunctionCallOption : IJsonModel { + internal InternalChatCompletionFunctionCallOption() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionFunctionCallOption)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter w } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter w #endif } } - writer.WriteEndObject(); } - InternalChatCompletionFunctionCallOption IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionFunctionCallOption IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionFunctionCallOption JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionFunctionCallOption)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionFunctionCallOption(document.RootElement, options); } - internal static InternalChatCompletionFunctionCallOption DeserializeInternalChatCompletionFunctionCallOption(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionFunctionCallOption DeserializeInternalChatCompletionFunctionCallOption(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionFunctionCallOption(name, serializedAdditionalRawData); + return new InternalChatCompletionFunctionCallOption(name, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalChatCompletionFunctionCallOption IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionFunctionCallOption IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionFunctionCallOption 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionFunctionCallOption(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalChatCompletionFunctionCallOption IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionFunctionCallOption FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionFunctionCallOption internalChatCompletionFunctionCallOption) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionFunctionCallOption(document.RootElement); + if (internalChatCompletionFunctionCallOption == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionFunctionCallOption, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionFunctionCallOption(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionFunctionCallOption(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionFunctionCallOption.cs b/src/Generated/Models/InternalChatCompletionFunctionCallOption.cs index 2cb95446c..bcc0e449d 100644 --- a/src/Generated/Models/InternalChatCompletionFunctionCallOption.cs +++ b/src/Generated/Models/InternalChatCompletionFunctionCallOption.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionFunctionCallOption { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionFunctionCallOption(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,16 +19,18 @@ public InternalChatCompletionFunctionCallOption(string name) Name = name; } - internal InternalChatCompletionFunctionCallOption(string name, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionFunctionCallOption(string name, IDictionary additionalBinaryDataProperties) { Name = name; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalChatCompletionFunctionCallOption() + public string Name { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; } } } diff --git a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.Serialization.cs b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.Serialization.cs index df7e5fe73..1f5d4d3ad 100644 --- a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,26 +15,31 @@ internal partial class InternalChatCompletionMessageToolCallChunkFunction : IJso { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionMessageToolCallChunkFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true && Optional.IsDefined(Arguments)) + if (Optional.IsDefined(Arguments) && _additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); - SerializeArgumentsValue(writer, options); + this.SerializeArgumentsValue(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8Js } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8Js #endif } } - writer.WriteEndObject(); } - InternalChatCompletionMessageToolCallChunkFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionMessageToolCallChunkFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionMessageToolCallChunkFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionMessageToolCallChunkFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionMessageToolCallChunkFunction(document.RootElement, options); } - internal static InternalChatCompletionMessageToolCallChunkFunction DeserializeInternalChatCompletionMessageToolCallChunkFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionMessageToolCallChunkFunction DeserializeInternalChatCompletionMessageToolCallChunkFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; BinaryData arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - DeserializeArgumentsValue(property, ref arguments); + DeserializeArgumentsValue(prop, ref arguments); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionMessageToolCallChunkFunction(name, arguments, serializedAdditionalRawData); + return new InternalChatCompletionMessageToolCallChunkFunction(name, arguments, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel } } - InternalChatCompletionMessageToolCallChunkFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionMessageToolCallChunkFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionMessageToolCallChunkFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionMessageToolCallChunkFunction(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalChatCompletionMessageToolCallChunkFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionMessageToolCallChunkFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionMessageToolCallChunkFunction internalChatCompletionMessageToolCallChunkFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionMessageToolCallChunkFunction(document.RootElement); + if (internalChatCompletionMessageToolCallChunkFunction == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionMessageToolCallChunkFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionMessageToolCallChunkFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionMessageToolCallChunkFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.cs b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.cs index 620712122..fded46a45 100644 --- a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.cs +++ b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkFunction.cs @@ -9,18 +9,25 @@ namespace OpenAI.Chat { internal partial class InternalChatCompletionMessageToolCallChunkFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalChatCompletionMessageToolCallChunkFunction() { } - internal InternalChatCompletionMessageToolCallChunkFunction(string name, BinaryData arguments, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionMessageToolCallChunkFunction(string name, BinaryData arguments, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkType.cs b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkType.cs index ea62bf0ab..105152fba 100644 --- a/src/Generated/Models/InternalChatCompletionMessageToolCallChunkType.cs +++ b/src/Generated/Models/InternalChatCompletionMessageToolCallChunkType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionMessageToolCallChunkType : IEquatable { private readonly string _value; + private const string FunctionValue = "function"; public InternalChatCompletionMessageToolCallChunkType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FunctionValue = "function"; + _value = value; + } public static InternalChatCompletionMessageToolCallChunkType Function { get; } = new InternalChatCompletionMessageToolCallChunkType(FunctionValue); + public static bool operator ==(InternalChatCompletionMessageToolCallChunkType left, InternalChatCompletionMessageToolCallChunkType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionMessageToolCallChunkType left, InternalChatCompletionMessageToolCallChunkType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionMessageToolCallChunkType(string value) => new InternalChatCompletionMessageToolCallChunkType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionMessageToolCallChunkType other && Equals(other); + public bool Equals(InternalChatCompletionMessageToolCallChunkType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.Serialization.cs b/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.Serialization.cs index 3729b14b2..48fde14d1 100644 --- a/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionMessageToolCallFunction : IJsonModel { + internal InternalChatCompletionMessageToolCallFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionMessageToolCallFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); - SerializeArgumentsValue(writer, options); + this.SerializeArgumentsValue(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWri #endif } } - writer.WriteEndObject(); } - InternalChatCompletionMessageToolCallFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionMessageToolCallFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionMessageToolCallFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionMessageToolCallFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionMessageToolCallFunction(document.RootElement, options); } - internal static InternalChatCompletionMessageToolCallFunction DeserializeInternalChatCompletionMessageToolCallFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionMessageToolCallFunction DeserializeInternalChatCompletionMessageToolCallFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; BinaryData arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - DeserializeArgumentsValue(property, ref arguments); + DeserializeArgumentsValue(prop, ref arguments); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionMessageToolCallFunction(name, arguments, serializedAdditionalRawData); + return new InternalChatCompletionMessageToolCallFunction(name, arguments, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Writ } } - InternalChatCompletionMessageToolCallFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionMessageToolCallFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionMessageToolCallFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionMessageToolCallFunction(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionMessageToolCallFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionMessageToolCallFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionMessageToolCallFunction internalChatCompletionMessageToolCallFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionMessageToolCallFunction(document.RootElement); + if (internalChatCompletionMessageToolCallFunction == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionMessageToolCallFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionMessageToolCallFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionMessageToolCallFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.cs b/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.cs index 88c406cb7..841322720 100644 --- a/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.cs +++ b/src/Generated/Models/InternalChatCompletionMessageToolCallFunction.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionMessageToolCallFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionMessageToolCallFunction(string name, BinaryData arguments) { Argument.AssertNotNull(name, nameof(name)); @@ -19,17 +21,19 @@ public InternalChatCompletionMessageToolCallFunction(string name, BinaryData arg Arguments = arguments; } - internal InternalChatCompletionMessageToolCallFunction(string name, BinaryData arguments, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionMessageToolCallFunction(string name, BinaryData arguments, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalChatCompletionMessageToolCallFunction() + public string Name { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; set; } } } diff --git a/src/Generated/Models/InternalChatCompletionNamedToolChoice.Serialization.cs b/src/Generated/Models/InternalChatCompletionNamedToolChoice.Serialization.cs index 447e3509c..c2d62dcba 100644 --- a/src/Generated/Models/InternalChatCompletionNamedToolChoice.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionNamedToolChoice.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionNamedToolChoice : IJsonModel { + internal InternalChatCompletionNamedToolChoice() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionNamedToolChoice)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalChatCompletionNamedToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionNamedToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionNamedToolChoice JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionNamedToolChoice)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionNamedToolChoice(document.RootElement, options); } - internal static InternalChatCompletionNamedToolChoice DeserializeInternalChatCompletionNamedToolChoice(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionNamedToolChoice DeserializeInternalChatCompletionNamedToolChoice(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalChatCompletionNamedToolChoiceType type = default; + InternalChatCompletionNamedToolChoiceType @type = default; InternalChatCompletionNamedToolChoiceFunction function = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalChatCompletionNamedToolChoiceType(property.Value.GetString()); + @type = new InternalChatCompletionNamedToolChoiceType(prop.Value.GetString()); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("function"u8)) { - function = InternalChatCompletionNamedToolChoiceFunction.DeserializeInternalChatCompletionNamedToolChoiceFunction(property.Value, options); + function = InternalChatCompletionNamedToolChoiceFunction.DeserializeInternalChatCompletionNamedToolChoiceFunction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionNamedToolChoice(type, function, serializedAdditionalRawData); + return new InternalChatCompletionNamedToolChoice(@type, function, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalChatCompletionNamedToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionNamedToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionNamedToolChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionNamedToolChoice(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionNamedToolChoice IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionNamedToolChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionNamedToolChoice internalChatCompletionNamedToolChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionNamedToolChoice(document.RootElement); + if (internalChatCompletionNamedToolChoice == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionNamedToolChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionNamedToolChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionNamedToolChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionNamedToolChoice.cs b/src/Generated/Models/InternalChatCompletionNamedToolChoice.cs index 4538d8136..31efb2d80 100644 --- a/src/Generated/Models/InternalChatCompletionNamedToolChoice.cs +++ b/src/Generated/Models/InternalChatCompletionNamedToolChoice.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionNamedToolChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionNamedToolChoice(InternalChatCompletionNamedToolChoiceFunction function) { Argument.AssertNotNull(function, nameof(function)); @@ -17,19 +19,21 @@ public InternalChatCompletionNamedToolChoice(InternalChatCompletionNamedToolChoi Function = function; } - internal InternalChatCompletionNamedToolChoice(InternalChatCompletionNamedToolChoiceType type, InternalChatCompletionNamedToolChoiceFunction function, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionNamedToolChoice(InternalChatCompletionNamedToolChoiceType @type, InternalChatCompletionNamedToolChoiceFunction function, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalChatCompletionNamedToolChoice() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalChatCompletionNamedToolChoiceType Type { get; } = InternalChatCompletionNamedToolChoiceType.Function; + public InternalChatCompletionNamedToolChoiceType Type { get; } = "function"; public InternalChatCompletionNamedToolChoiceFunction Function { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.Serialization.cs b/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.Serialization.cs index 8e0e339e3..4c3b8a036 100644 --- a/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionNamedToolChoiceFunction : IJsonModel { + internal InternalChatCompletionNamedToolChoiceFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionNamedToolChoiceFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWri #endif } } - writer.WriteEndObject(); } - InternalChatCompletionNamedToolChoiceFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionNamedToolChoiceFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionNamedToolChoiceFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionNamedToolChoiceFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionNamedToolChoiceFunction(document.RootElement, options); } - internal static InternalChatCompletionNamedToolChoiceFunction DeserializeInternalChatCompletionNamedToolChoiceFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionNamedToolChoiceFunction DeserializeInternalChatCompletionNamedToolChoiceFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionNamedToolChoiceFunction(name, serializedAdditionalRawData); + return new InternalChatCompletionNamedToolChoiceFunction(name, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Writ } } - InternalChatCompletionNamedToolChoiceFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionNamedToolChoiceFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionNamedToolChoiceFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionNamedToolChoiceFunction(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalChatCompletionNamedToolChoiceFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionNamedToolChoiceFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionNamedToolChoiceFunction internalChatCompletionNamedToolChoiceFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionNamedToolChoiceFunction(document.RootElement); + if (internalChatCompletionNamedToolChoiceFunction == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionNamedToolChoiceFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionNamedToolChoiceFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionNamedToolChoiceFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.cs b/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.cs index 5097bcb79..c810baf52 100644 --- a/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.cs +++ b/src/Generated/Models/InternalChatCompletionNamedToolChoiceFunction.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionNamedToolChoiceFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionNamedToolChoiceFunction(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,16 +19,18 @@ public InternalChatCompletionNamedToolChoiceFunction(string name) Name = name; } - internal InternalChatCompletionNamedToolChoiceFunction(string name, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionNamedToolChoiceFunction(string name, IDictionary additionalBinaryDataProperties) { Name = name; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalChatCompletionNamedToolChoiceFunction() + public string Name { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; } } } diff --git a/src/Generated/Models/InternalChatCompletionNamedToolChoiceType.cs b/src/Generated/Models/InternalChatCompletionNamedToolChoiceType.cs index b5eda303b..0fe3d7180 100644 --- a/src/Generated/Models/InternalChatCompletionNamedToolChoiceType.cs +++ b/src/Generated/Models/InternalChatCompletionNamedToolChoiceType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionNamedToolChoiceType : IEquatable { private readonly string _value; + private const string FunctionValue = "function"; public InternalChatCompletionNamedToolChoiceType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FunctionValue = "function"; + _value = value; + } public static InternalChatCompletionNamedToolChoiceType Function { get; } = new InternalChatCompletionNamedToolChoiceType(FunctionValue); + public static bool operator ==(InternalChatCompletionNamedToolChoiceType left, InternalChatCompletionNamedToolChoiceType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionNamedToolChoiceType left, InternalChatCompletionNamedToolChoiceType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionNamedToolChoiceType(string value) => new InternalChatCompletionNamedToolChoiceType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionNamedToolChoiceType other && Equals(other); + public bool Equals(InternalChatCompletionNamedToolChoiceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.Serialization.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.Serialization.cs index f348a091d..5c1248e27 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartImage : IJsonModel { + internal InternalChatCompletionRequestMessageContentPartImage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionRequestMessageContentPartImage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("image_url") != true) + if (_additionalBinaryDataProperties?.ContainsKey("image_url") != true) { writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(ImageUrl, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8 } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8 #endif } } - writer.WriteEndObject(); } - InternalChatCompletionRequestMessageContentPartImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionRequestMessageContentPartImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionRequestMessageContentPartImage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartImage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionRequestMessageContentPartImage(document.RootElement, options); } - internal static InternalChatCompletionRequestMessageContentPartImage DeserializeInternalChatCompletionRequestMessageContentPartImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionRequestMessageContentPartImage DeserializeInternalChatCompletionRequestMessageContentPartImage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalChatCompletionRequestMessageContentPartImageType type = default; + InternalChatCompletionRequestMessageContentPartImageType @type = default; InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalChatCompletionRequestMessageContentPartImageType(property.Value.GetString()); + @type = new InternalChatCompletionRequestMessageContentPartImageType(prop.Value.GetString()); continue; } - if (property.NameEquals("image_url"u8)) + if (prop.NameEquals("image_url"u8)) { - imageUrl = InternalChatCompletionRequestMessageContentPartImageImageUrl.DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(property.Value, options); + imageUrl = InternalChatCompletionRequestMessageContentPartImageImageUrl.DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionRequestMessageContentPartImage(type, imageUrl, serializedAdditionalRawData); + return new InternalChatCompletionRequestMessageContentPartImage(@type, imageUrl, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionRequestMessageContentPartImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionRequestMessageContentPartImage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionRequestMessageContentPartImage(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionRequestMessageContentPartImage IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionRequestMessageContentPartImage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionRequestMessageContentPartImage internalChatCompletionRequestMessageContentPartImage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionRequestMessageContentPartImage(document.RootElement); + if (internalChatCompletionRequestMessageContentPartImage == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionRequestMessageContentPartImage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionRequestMessageContentPartImage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionRequestMessageContentPartImage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.cs index 97fb55045..2b8d104c8 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImage.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartImage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionRequestMessageContentPartImage(InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl) { Argument.AssertNotNull(imageUrl, nameof(imageUrl)); @@ -17,19 +19,21 @@ public InternalChatCompletionRequestMessageContentPartImage(InternalChatCompleti ImageUrl = imageUrl; } - internal InternalChatCompletionRequestMessageContentPartImage(InternalChatCompletionRequestMessageContentPartImageType type, InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionRequestMessageContentPartImage(InternalChatCompletionRequestMessageContentPartImageType @type, InternalChatCompletionRequestMessageContentPartImageImageUrl imageUrl, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; ImageUrl = imageUrl; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalChatCompletionRequestMessageContentPartImage() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalChatCompletionRequestMessageContentPartImageType Type { get; } = InternalChatCompletionRequestMessageContentPartImageType.ImageUrl; + public InternalChatCompletionRequestMessageContentPartImageType Type { get; } = "image_url"; public InternalChatCompletionRequestMessageContentPartImageImageUrl ImageUrl { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.Serialization.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.Serialization.cs index e84cdd271..514e40e67 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartImageImageUrl : IJsonModel { + internal InternalChatCompletionRequestMessageContentPartImageImageUrl() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionRequestMessageContentPartImageImageUrl)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("url") != true) - { - writer.WritePropertyName("url"u8); - writer.WriteStringValue(Url); - } - if (SerializedAdditionalRawData?.ContainsKey("detail") != true && Optional.IsDefined(Detail)) + if (Optional.IsDefined(Detail) && _additionalBinaryDataProperties?.ContainsKey("detail") != true) { writer.WritePropertyName("detail"u8); writer.WriteStringValue(Detail.Value.ToString()); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("url") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Wr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,63 +60,59 @@ void IJsonModel.Wr #endif } } - writer.WriteEndObject(); } - InternalChatCompletionRequestMessageContentPartImageImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionRequestMessageContentPartImageImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionRequestMessageContentPartImageImageUrl JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartImageImageUrl)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(document.RootElement, options); } - internal static InternalChatCompletionRequestMessageContentPartImageImageUrl DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionRequestMessageContentPartImageImageUrl DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string url = default; ChatImageDetailLevel? detail = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string url = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) + if (prop.NameEquals("detail"u8)) { - url = property.Value.GetString(); - continue; - } - if (property.NameEquals("detail"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - detail = new ChatImageDetailLevel(property.Value.GetString()); + detail = new ChatImageDetailLevel(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("url"u8)) + { + url = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionRequestMessageContentPartImageImageUrl(url, detail, serializedAdditionalRawData); + return new InternalChatCompletionRequestMessageContentPartImageImageUrl(detail, url, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -116,15 +122,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionRequestMessageContentPartImageImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionRequestMessageContentPartImageImageUrl 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(document.RootElement, options); } default: @@ -134,15 +141,20 @@ InternalChatCompletionRequestMessageContentPartImageImageUrl IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionRequestMessageContentPartImageImageUrl FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionRequestMessageContentPartImageImageUrl internalChatCompletionRequestMessageContentPartImageImageUrl) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(document.RootElement); + if (internalChatCompletionRequestMessageContentPartImageImageUrl == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionRequestMessageContentPartImageImageUrl, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionRequestMessageContentPartImageImageUrl(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionRequestMessageContentPartImageImageUrl(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs index e0e87271f..ceb265278 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageImageUrl.cs @@ -9,11 +9,14 @@ namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartImageImageUrl { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal InternalChatCompletionRequestMessageContentPartImageImageUrl() + public ChatImageDetailLevel? Detail { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public ChatImageDetailLevel? Detail { get; set; } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageType.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageType.cs index 2a1100017..90bc6204d 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageType.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartImageType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionRequestMessageContentPartImageType : IEquatable { private readonly string _value; + private const string ImageUrlValue = "image_url"; public InternalChatCompletionRequestMessageContentPartImageType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ImageUrlValue = "image_url"; + _value = value; + } public static InternalChatCompletionRequestMessageContentPartImageType ImageUrl { get; } = new InternalChatCompletionRequestMessageContentPartImageType(ImageUrlValue); + public static bool operator ==(InternalChatCompletionRequestMessageContentPartImageType left, InternalChatCompletionRequestMessageContentPartImageType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionRequestMessageContentPartImageType left, InternalChatCompletionRequestMessageContentPartImageType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionRequestMessageContentPartImageType(string value) => new InternalChatCompletionRequestMessageContentPartImageType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionRequestMessageContentPartImageType other && Equals(other); + public bool Equals(InternalChatCompletionRequestMessageContentPartImageType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs index 093b83c78..0bd526080 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartRefusal : IJsonModel { + internal InternalChatCompletionRequestMessageContentPartRefusal() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionRequestMessageContentPartRefusal)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true) + if (_additionalBinaryDataProperties?.ContainsKey("refusal") != true) { writer.WritePropertyName("refusal"u8); writer.WriteStringValue(Refusal); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Ut } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Ut #endif } } - writer.WriteEndObject(); } - InternalChatCompletionRequestMessageContentPartRefusal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionRequestMessageContentPartRefusal IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionRequestMessageContentPartRefusal JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartRefusal)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement, options); } - internal static InternalChatCompletionRequestMessageContentPartRefusal DeserializeInternalChatCompletionRequestMessageContentPartRefusal(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionRequestMessageContentPartRefusal DeserializeInternalChatCompletionRequestMessageContentPartRefusal(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalChatCompletionRequestMessageContentPartRefusalType type = default; + InternalChatCompletionRequestMessageContentPartRefusalType @type = default; string refusal = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalChatCompletionRequestMessageContentPartRefusalType(property.Value.GetString()); + @type = new InternalChatCompletionRequestMessageContentPartRefusalType(prop.Value.GetString()); continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("refusal"u8)) { - refusal = property.Value.GetString(); + refusal = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionRequestMessageContentPartRefusal(type, refusal, serializedAdditionalRawData); + return new InternalChatCompletionRequestMessageContentPartRefusal(@type, refusal, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionRequestMessageContentPartRefusal IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionRequestMessageContentPartRefusal 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionRequestMessageContentPartRefusal IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionRequestMessageContentPartRefusal FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionRequestMessageContentPartRefusal internalChatCompletionRequestMessageContentPartRefusal) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement); + if (internalChatCompletionRequestMessageContentPartRefusal == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionRequestMessageContentPartRefusal, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionRequestMessageContentPartRefusal(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionRequestMessageContentPartRefusal(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs index ea0eaa097..458939ce0 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusal.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartRefusal { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionRequestMessageContentPartRefusal(string refusal) { Argument.AssertNotNull(refusal, nameof(refusal)); @@ -17,19 +19,21 @@ public InternalChatCompletionRequestMessageContentPartRefusal(string refusal) Refusal = refusal; } - internal InternalChatCompletionRequestMessageContentPartRefusal(InternalChatCompletionRequestMessageContentPartRefusalType type, string refusal, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionRequestMessageContentPartRefusal(InternalChatCompletionRequestMessageContentPartRefusalType @type, string refusal, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Refusal = refusal; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalChatCompletionRequestMessageContentPartRefusal() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalChatCompletionRequestMessageContentPartRefusalType Type { get; } = InternalChatCompletionRequestMessageContentPartRefusalType.Refusal; + public InternalChatCompletionRequestMessageContentPartRefusalType Type { get; } = "refusal"; public string Refusal { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs index d1c3e8498..1096b7c85 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartRefusalType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionRequestMessageContentPartRefusalType : IEquatable { private readonly string _value; + private const string RefusalValue = "refusal"; public InternalChatCompletionRequestMessageContentPartRefusalType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string RefusalValue = "refusal"; + _value = value; + } public static InternalChatCompletionRequestMessageContentPartRefusalType Refusal { get; } = new InternalChatCompletionRequestMessageContentPartRefusalType(RefusalValue); + public static bool operator ==(InternalChatCompletionRequestMessageContentPartRefusalType left, InternalChatCompletionRequestMessageContentPartRefusalType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionRequestMessageContentPartRefusalType left, InternalChatCompletionRequestMessageContentPartRefusalType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionRequestMessageContentPartRefusalType(string value) => new InternalChatCompletionRequestMessageContentPartRefusalType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionRequestMessageContentPartRefusalType other && Equals(other); + public bool Equals(InternalChatCompletionRequestMessageContentPartRefusalType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.Serialization.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.Serialization.cs index bec3c465f..d318473d8 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartText : IJsonModel { + internal InternalChatCompletionRequestMessageContentPartText() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionRequestMessageContentPartText)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8J } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8J #endif } } - writer.WriteEndObject(); } - InternalChatCompletionRequestMessageContentPartText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionRequestMessageContentPartText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionRequestMessageContentPartText JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionRequestMessageContentPartText)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionRequestMessageContentPartText(document.RootElement, options); } - internal static InternalChatCompletionRequestMessageContentPartText DeserializeInternalChatCompletionRequestMessageContentPartText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionRequestMessageContentPartText DeserializeInternalChatCompletionRequestMessageContentPartText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalChatCompletionRequestMessageContentPartTextType type = default; + InternalChatCompletionRequestMessageContentPartTextType @type = default; string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalChatCompletionRequestMessageContentPartTextType(property.Value.GetString()); + @type = new InternalChatCompletionRequestMessageContentPartTextType(prop.Value.GetString()); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionRequestMessageContentPartText(type, text, serializedAdditionalRawData); + return new InternalChatCompletionRequestMessageContentPartText(@type, text, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionRequestMessageContentPartText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionRequestMessageContentPartText 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionRequestMessageContentPartText(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionRequestMessageContentPartText IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionRequestMessageContentPartText FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionRequestMessageContentPartText internalChatCompletionRequestMessageContentPartText) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionRequestMessageContentPartText(document.RootElement); + if (internalChatCompletionRequestMessageContentPartText == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionRequestMessageContentPartText, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionRequestMessageContentPartText(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionRequestMessageContentPartText(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.cs index 09645f628..e97d6a9c4 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartText.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionRequestMessageContentPartText { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionRequestMessageContentPartText(string text) { Argument.AssertNotNull(text, nameof(text)); @@ -17,19 +19,21 @@ public InternalChatCompletionRequestMessageContentPartText(string text) Text = text; } - internal InternalChatCompletionRequestMessageContentPartText(InternalChatCompletionRequestMessageContentPartTextType type, string text, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionRequestMessageContentPartText(InternalChatCompletionRequestMessageContentPartTextType @type, string text, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalChatCompletionRequestMessageContentPartText() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalChatCompletionRequestMessageContentPartTextType Type { get; } = InternalChatCompletionRequestMessageContentPartTextType.Text; + public InternalChatCompletionRequestMessageContentPartTextType Type { get; } = "text"; public string Text { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartTextType.cs b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartTextType.cs index 8c58795bb..5f8e3c80d 100644 --- a/src/Generated/Models/InternalChatCompletionRequestMessageContentPartTextType.cs +++ b/src/Generated/Models/InternalChatCompletionRequestMessageContentPartTextType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionRequestMessageContentPartTextType : IEquatable { private readonly string _value; + private const string TextValue = "text"; public InternalChatCompletionRequestMessageContentPartTextType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextValue = "text"; + _value = value; + } public static InternalChatCompletionRequestMessageContentPartTextType Text { get; } = new InternalChatCompletionRequestMessageContentPartTextType(TextValue); + public static bool operator ==(InternalChatCompletionRequestMessageContentPartTextType left, InternalChatCompletionRequestMessageContentPartTextType right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionRequestMessageContentPartTextType left, InternalChatCompletionRequestMessageContentPartTextType right) => !left.Equals(right); + public static implicit operator InternalChatCompletionRequestMessageContentPartTextType(string value) => new InternalChatCompletionRequestMessageContentPartTextType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionRequestMessageContentPartTextType other && Equals(other); + public bool Equals(InternalChatCompletionRequestMessageContentPartTextType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionResponseMessage.Serialization.cs b/src/Generated/Models/InternalChatCompletionResponseMessage.Serialization.cs index 024a984bc..9f3af8c10 100644 --- a/src/Generated/Models/InternalChatCompletionResponseMessage.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionResponseMessage.Serialization.cs @@ -7,33 +7,31 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionResponseMessage : IJsonModel { + internal InternalChatCompletionResponseMessage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionResponseMessage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) - { - if (Content != null) - { - writer.WritePropertyName("content"u8); - SerializeContentValue(writer, options); - } - else - { - writer.WriteNull("content"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true) + if (_additionalBinaryDataProperties?.ContainsKey("refusal") != true) { if (Refusal != null) { @@ -42,32 +40,44 @@ void IJsonModel.Write(Utf8JsonWriter writ } else { - writer.WriteNull("refusal"); + writer.WriteNull("refusal"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true && Optional.IsCollectionDefined(ToolCalls)) + if (true && Optional.IsCollectionDefined(ToolCalls) && _additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); - foreach (var item in ToolCalls) + foreach (ChatToolCall item in ToolCalls) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) { writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("function_call") != true && Optional.IsDefined(FunctionCall)) + if (_additionalBinaryDataProperties?.ContainsKey("content") != true) + { + if (Content != null) + { + writer.WritePropertyName("content"u8); + this.SerializeContentValue(writer, options); + } + else + { + writer.WriteNull("content"u8); + } + } + if (Optional.IsDefined(FunctionCall) && _additionalBinaryDataProperties?.ContainsKey("function_call") != true) { writer.WritePropertyName("function_call"u8); writer.WriteObjectValue(FunctionCall, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -75,7 +85,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -84,102 +94,98 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalChatCompletionResponseMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionResponseMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionResponseMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionResponseMessage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionResponseMessage(document.RootElement, options); } - internal static InternalChatCompletionResponseMessage DeserializeInternalChatCompletionResponseMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionResponseMessage DeserializeInternalChatCompletionResponseMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ChatMessageContent content = default; string refusal = default; IReadOnlyList toolCalls = default; - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; + ChatMessageContent content = default; ChatFunctionCall functionCall = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) - { - DeserializeContentValue(property, ref content); - continue; - } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("refusal"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { refusal = null; continue; } - refusal = property.Value.GetString(); + refusal = prop.Value.GetString(); continue; } - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatToolCall.DeserializeChatToolCall(item, options)); } toolCalls = array; continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("role"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("function_call"u8)) + if (prop.NameEquals("content"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + DeserializeContentValue(prop, ref content); + continue; + } + if (prop.NameEquals("function_call"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - functionCall = ChatFunctionCall.DeserializeChatFunctionCall(property.Value, options); + functionCall = ChatFunctionCall.DeserializeChatFunctionCall(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. return new InternalChatCompletionResponseMessage( - content ?? new ChatMessageContent(), refusal, toolCalls ?? new ChangeTrackingList(), role, + content ?? new ChatMessageContent(), functionCall, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -189,15 +195,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalChatCompletionResponseMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionResponseMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionResponseMessage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionResponseMessage(document.RootElement, options); } default: @@ -207,15 +214,20 @@ InternalChatCompletionResponseMessage IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionResponseMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionResponseMessage internalChatCompletionResponseMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionResponseMessage(document.RootElement); + if (internalChatCompletionResponseMessage == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionResponseMessage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionResponseMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionResponseMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionResponseMessage.cs b/src/Generated/Models/InternalChatCompletionResponseMessage.cs index 155c73932..97b362414 100644 --- a/src/Generated/Models/InternalChatCompletionResponseMessage.cs +++ b/src/Generated/Models/InternalChatCompletionResponseMessage.cs @@ -4,33 +4,39 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionResponseMessage { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalChatCompletionResponseMessage(ChatMessageContent content, string refusal) + private protected IDictionary _additionalBinaryDataProperties; + + internal InternalChatCompletionResponseMessage(string refusal, ChatMessageContent content) { - Content = content; Refusal = refusal; ToolCalls = new ChangeTrackingList(); + Content = content; } - internal InternalChatCompletionResponseMessage(ChatMessageContent content, string refusal, IReadOnlyList toolCalls, ChatMessageRole role, ChatFunctionCall functionCall, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionResponseMessage(string refusal, IReadOnlyList toolCalls, Chat.ChatMessageRole role, ChatMessageContent content, ChatFunctionCall functionCall, IDictionary additionalBinaryDataProperties) { - Content = content; Refusal = refusal; ToolCalls = toolCalls; Role = role; + Content = content; FunctionCall = functionCall; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalChatCompletionResponseMessage() - { - } public string Refusal { get; } + public IReadOnlyList ToolCalls { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.Serialization.cs b/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.Serialization.cs index 919dcf8ef..4bea570ba 100644 --- a/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatCompletionResponseMessageFunctionCall : IJsonModel { + internal InternalChatCompletionResponseMessageFunctionCall() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionResponseMessageFunctionCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8Jso } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8Jso #endif } } - writer.WriteEndObject(); } - InternalChatCompletionResponseMessageFunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionResponseMessageFunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionResponseMessageFunctionCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionResponseMessageFunctionCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionResponseMessageFunctionCall(document.RootElement, options); } - internal static InternalChatCompletionResponseMessageFunctionCall DeserializeInternalChatCompletionResponseMessageFunctionCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionResponseMessageFunctionCall DeserializeInternalChatCompletionResponseMessageFunctionCall(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; string arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - arguments = property.Value.GetString(); + arguments = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionResponseMessageFunctionCall(name, arguments, serializedAdditionalRawData); + return new InternalChatCompletionResponseMessageFunctionCall(name, arguments, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel. } } - InternalChatCompletionResponseMessageFunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionResponseMessageFunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionResponseMessageFunctionCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionResponseMessageFunctionCall(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalChatCompletionResponseMessageFunctionCall IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionResponseMessageFunctionCall FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionResponseMessageFunctionCall internalChatCompletionResponseMessageFunctionCall) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionResponseMessageFunctionCall(document.RootElement); + if (internalChatCompletionResponseMessageFunctionCall == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionResponseMessageFunctionCall, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionResponseMessageFunctionCall(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionResponseMessageFunctionCall(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.cs b/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.cs index 7eaa7f37d..cc4c86f3e 100644 --- a/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.cs +++ b/src/Generated/Models/InternalChatCompletionResponseMessageFunctionCall.cs @@ -9,28 +9,29 @@ namespace OpenAI.Chat { internal partial class InternalChatCompletionResponseMessageFunctionCall { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalChatCompletionResponseMessageFunctionCall(string name, string arguments) { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(arguments, nameof(arguments)); - Name = name; Arguments = arguments; } - internal InternalChatCompletionResponseMessageFunctionCall(string name, string arguments, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionResponseMessageFunctionCall(string name, string arguments, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalChatCompletionResponseMessageFunctionCall() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; } + public string Arguments { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionResponseMessageRole.cs b/src/Generated/Models/InternalChatCompletionResponseMessageRole.cs index 0794f1019..69b375aaf 100644 --- a/src/Generated/Models/InternalChatCompletionResponseMessageRole.cs +++ b/src/Generated/Models/InternalChatCompletionResponseMessageRole.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionResponseMessageRole : IEquatable { private readonly string _value; + private const string AssistantValue = "assistant"; public InternalChatCompletionResponseMessageRole(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AssistantValue = "assistant"; + _value = value; + } public static InternalChatCompletionResponseMessageRole Assistant { get; } = new InternalChatCompletionResponseMessageRole(AssistantValue); + public static bool operator ==(InternalChatCompletionResponseMessageRole left, InternalChatCompletionResponseMessageRole right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionResponseMessageRole left, InternalChatCompletionResponseMessageRole right) => !left.Equals(right); + public static implicit operator InternalChatCompletionResponseMessageRole(string value) => new InternalChatCompletionResponseMessageRole(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionResponseMessageRole other && Equals(other); + public bool Equals(InternalChatCompletionResponseMessageRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatCompletionStreamOptions.Serialization.cs b/src/Generated/Models/InternalChatCompletionStreamOptions.Serialization.cs index bd3f2eb23..cf88a53b3 100644 --- a/src/Generated/Models/InternalChatCompletionStreamOptions.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionStreamOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,21 +15,26 @@ internal partial class InternalChatCompletionStreamOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionStreamOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("include_usage") != true && Optional.IsDefined(IncludeUsage)) + if (Optional.IsDefined(IncludeUsage) && _additionalBinaryDataProperties?.ContainsKey("include_usage") != true) { writer.WritePropertyName("include_usage"u8); writer.WriteBooleanValue(IncludeUsage.Value); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter writer } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,57 +51,53 @@ void IJsonModel.Write(Utf8JsonWriter writer #endif } } - writer.WriteEndObject(); } - InternalChatCompletionStreamOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionStreamOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionStreamOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionStreamOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionStreamOptions(document.RootElement, options); } - internal static InternalChatCompletionStreamOptions DeserializeInternalChatCompletionStreamOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionStreamOptions DeserializeInternalChatCompletionStreamOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } bool? includeUsage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("include_usage"u8)) + if (prop.NameEquals("include_usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - includeUsage = property.Value.GetBoolean(); + includeUsage = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatCompletionStreamOptions(includeUsage, serializedAdditionalRawData); + return new InternalChatCompletionStreamOptions(includeUsage, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -105,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - InternalChatCompletionStreamOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionStreamOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionStreamOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionStreamOptions(document.RootElement, options); } default: @@ -123,15 +126,20 @@ InternalChatCompletionStreamOptions IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionStreamOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionStreamOptions internalChatCompletionStreamOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionStreamOptions(document.RootElement); + if (internalChatCompletionStreamOptions == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionStreamOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionStreamOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionStreamOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionStreamOptions.cs b/src/Generated/Models/InternalChatCompletionStreamOptions.cs index 65d1cc3a1..c8a6db7a6 100644 --- a/src/Generated/Models/InternalChatCompletionStreamOptions.cs +++ b/src/Generated/Models/InternalChatCompletionStreamOptions.cs @@ -9,17 +9,24 @@ namespace OpenAI.Chat { internal partial class InternalChatCompletionStreamOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalChatCompletionStreamOptions() { } - internal InternalChatCompletionStreamOptions(bool? includeUsage, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionStreamOptions(bool? includeUsage, IDictionary additionalBinaryDataProperties) { IncludeUsage = includeUsage; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public bool? IncludeUsage { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionStreamResponseDelta.Serialization.cs b/src/Generated/Models/InternalChatCompletionStreamResponseDelta.Serialization.cs index 4925803a5..e67571f75 100644 --- a/src/Generated/Models/InternalChatCompletionStreamResponseDelta.Serialization.cs +++ b/src/Generated/Models/InternalChatCompletionStreamResponseDelta.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,61 +15,66 @@ internal partial class InternalChatCompletionStreamResponseDelta : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalChatCompletionStreamResponseDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - // CUSTOM: Check inner collection is defined. - if (SerializedAdditionalRawData?.ContainsKey("content") != true && Optional.IsDefined(Content) && Content.IsInnerCollectionDefined()) - { - if (Content != null) - { - writer.WritePropertyName("content"u8); - SerializeContentValue(writer, options); - } - else - { - writer.WriteNull("content"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("function_call") != true && Optional.IsDefined(FunctionCall)) + if (Optional.IsDefined(FunctionCall) && _additionalBinaryDataProperties?.ContainsKey("function_call") != true) { writer.WritePropertyName("function_call"u8); writer.WriteObjectValue(FunctionCall, options); } - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true && Optional.IsCollectionDefined(ToolCalls)) + if (true && Optional.IsCollectionDefined(ToolCalls) && _additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); - foreach (var item in ToolCalls) + foreach (StreamingChatToolCallUpdate item in ToolCalls) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("role") != true && Optional.IsDefined(Role)) + if (Optional.IsDefined(Refusal) && _additionalBinaryDataProperties?.ContainsKey("refusal") != true) + { + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"u8); + } + } + if (Optional.IsDefined(Role) && _additionalBinaryDataProperties?.ContainsKey("role") != true) { writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.Value.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && Optional.IsDefined(Refusal)) + // CUSTOM: Check inner collection is defined. + if (Optional.IsDefined(Content) && _additionalBinaryDataProperties?.ContainsKey("content") != true && Content.IsInnerCollectionDefined()) { - if (Refusal != null) + if (Content != null) { - writer.WritePropertyName("refusal"u8); - writer.WriteStringValue(Refusal); + writer.WritePropertyName("content"u8); + this.SerializeContentValue(writer, options); } else { - writer.WriteNull("refusal"); + writer.WriteNull("content"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -76,7 +82,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -85,106 +91,102 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalChatCompletionStreamResponseDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalChatCompletionStreamResponseDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalChatCompletionStreamResponseDelta JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalChatCompletionStreamResponseDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatCompletionStreamResponseDelta(document.RootElement, options); } - internal static InternalChatCompletionStreamResponseDelta DeserializeInternalChatCompletionStreamResponseDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatCompletionStreamResponseDelta DeserializeInternalChatCompletionStreamResponseDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ChatMessageContent content = default; StreamingChatFunctionCallUpdate functionCall = default; IReadOnlyList toolCalls = default; - ChatMessageRole? role = default; string refusal = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Chat.ChatMessageRole? role = default; + ChatMessageContent content = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("function_call"u8)) { - DeserializeContentValue(property, ref content); - continue; - } - if (property.NameEquals("function_call"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - functionCall = StreamingChatFunctionCallUpdate.DeserializeStreamingChatFunctionCallUpdate(property.Value, options); + functionCall = StreamingChatFunctionCallUpdate.DeserializeStreamingChatFunctionCallUpdate(prop.Value, options); continue; } - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(StreamingChatToolCallUpdate.DeserializeStreamingChatToolCallUpdate(item, options)); } toolCalls = array; continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("refusal"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + refusal = null; continue; } - role = property.Value.GetString().ToChatMessageRole(); + refusal = prop.Value.GetString(); continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - refusal = null; continue; } - refusal = property.Value.GetString(); + role = prop.Value.GetString().ToChatMessageRole(); + continue; + } + if (prop.NameEquals("content"u8)) + { + DeserializeContentValue(prop, ref content); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. return new InternalChatCompletionStreamResponseDelta( - content ?? new ChatMessageContent(), functionCall, toolCalls ?? new ChangeTrackingList(), - role, refusal, - serializedAdditionalRawData); + role, + content ?? new ChatMessageContent(), + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -194,15 +196,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalChatCompletionStreamResponseDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatCompletionStreamResponseDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalChatCompletionStreamResponseDelta 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatCompletionStreamResponseDelta(document.RootElement, options); } default: @@ -212,15 +215,20 @@ InternalChatCompletionStreamResponseDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalChatCompletionStreamResponseDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatCompletionStreamResponseDelta internalChatCompletionStreamResponseDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatCompletionStreamResponseDelta(document.RootElement); + if (internalChatCompletionStreamResponseDelta == null) + { + return null; + } + return BinaryContent.Create(internalChatCompletionStreamResponseDelta, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalChatCompletionStreamResponseDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatCompletionStreamResponseDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs b/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs index e2d4ae3ad..dba391eaf 100644 --- a/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs +++ b/src/Generated/Models/InternalChatCompletionStreamResponseDelta.cs @@ -9,19 +9,28 @@ namespace OpenAI.Chat { internal partial class InternalChatCompletionStreamResponseDelta { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal InternalChatCompletionStreamResponseDelta(ChatMessageContent content, StreamingChatFunctionCallUpdate functionCall, IReadOnlyList toolCalls, ChatMessageRole? role, string refusal, IDictionary serializedAdditionalRawData) + internal InternalChatCompletionStreamResponseDelta(StreamingChatFunctionCallUpdate functionCall, IReadOnlyList toolCalls, string refusal, Chat.ChatMessageRole? role, ChatMessageContent content, IDictionary additionalBinaryDataProperties) { - Content = content; FunctionCall = functionCall; ToolCalls = toolCalls; - Role = role; Refusal = refusal; - SerializedAdditionalRawData = serializedAdditionalRawData; + Role = role; + Content = content; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public StreamingChatFunctionCallUpdate FunctionCall { get; } + public IReadOnlyList ToolCalls { get; } + public string Refusal { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalChatCompletionStreamResponseDeltaRole.cs b/src/Generated/Models/InternalChatCompletionStreamResponseDeltaRole.cs index 07df77e42..c39d97b59 100644 --- a/src/Generated/Models/InternalChatCompletionStreamResponseDeltaRole.cs +++ b/src/Generated/Models/InternalChatCompletionStreamResponseDeltaRole.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalChatCompletionStreamResponseDeltaRole : IEquatable { private readonly string _value; - - public InternalChatCompletionStreamResponseDeltaRole(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string SystemValue = "system"; private const string UserValue = "user"; private const string AssistantValue = "assistant"; private const string ToolValue = "tool"; + public InternalChatCompletionStreamResponseDeltaRole(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalChatCompletionStreamResponseDeltaRole System { get; } = new InternalChatCompletionStreamResponseDeltaRole(SystemValue); + public static InternalChatCompletionStreamResponseDeltaRole User { get; } = new InternalChatCompletionStreamResponseDeltaRole(UserValue); + public static InternalChatCompletionStreamResponseDeltaRole Assistant { get; } = new InternalChatCompletionStreamResponseDeltaRole(AssistantValue); + public static InternalChatCompletionStreamResponseDeltaRole Tool { get; } = new InternalChatCompletionStreamResponseDeltaRole(ToolValue); + public static bool operator ==(InternalChatCompletionStreamResponseDeltaRole left, InternalChatCompletionStreamResponseDeltaRole right) => left.Equals(right); + public static bool operator !=(InternalChatCompletionStreamResponseDeltaRole left, InternalChatCompletionStreamResponseDeltaRole right) => !left.Equals(right); + public static implicit operator InternalChatCompletionStreamResponseDeltaRole(string value) => new InternalChatCompletionStreamResponseDeltaRole(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalChatCompletionStreamResponseDeltaRole other && Equals(other); + public bool Equals(InternalChatCompletionStreamResponseDeltaRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs b/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs index 3e555b657..22c9f1605 100644 --- a/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs +++ b/src/Generated/Models/InternalChatResponseFormatJsonObject.Serialization.cs @@ -7,55 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatResponseFormatJsonObject : IJsonModel { - InternalChatResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonObject)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + InternalChatResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalChatResponseFormatJsonObject)JsonModelCreateCore(ref reader, options); + + protected override ChatResponseFormat 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(InternalChatResponseFormatJsonObject)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatResponseFormatJsonObject(document.RootElement, options); } - internal static InternalChatResponseFormatJsonObject DeserializeInternalChatResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatResponseFormatJsonObject DeserializeInternalChatResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "json_object"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatResponseFormatJsonObject(type, serializedAdditionalRawData); + return new InternalChatResponseFormatJsonObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -65,15 +73,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - InternalChatResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalChatResponseFormatJsonObject)PersistableModelCreateCore(data, options); + protected override ChatResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatResponseFormatJsonObject(document.RootElement, options); } default: @@ -83,15 +92,20 @@ InternalChatResponseFormatJsonObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalChatResponseFormatJsonObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatResponseFormatJsonObject internalChatResponseFormatJsonObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatResponseFormatJsonObject(document.RootElement); + if (internalChatResponseFormatJsonObject == null) + { + return null; + } + return BinaryContent.Create(internalChatResponseFormatJsonObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalChatResponseFormatJsonObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatResponseFormatJsonObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatResponseFormatJsonObject.cs b/src/Generated/Models/InternalChatResponseFormatJsonObject.cs index a3d489404..28d430907 100644 --- a/src/Generated/Models/InternalChatResponseFormatJsonObject.cs +++ b/src/Generated/Models/InternalChatResponseFormatJsonObject.cs @@ -9,12 +9,11 @@ namespace OpenAI.Chat { internal partial class InternalChatResponseFormatJsonObject : ChatResponseFormat { - public InternalChatResponseFormatJsonObject() + public InternalChatResponseFormatJsonObject() : base("json_object") { - Type = "json_object"; } - internal InternalChatResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalChatResponseFormatJsonObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs b/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs index c2b875ee6..a22d9777b 100644 --- a/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs +++ b/src/Generated/Models/InternalChatResponseFormatJsonSchema.Serialization.cs @@ -7,62 +7,79 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Internal; namespace OpenAI.Chat { internal partial class InternalChatResponseFormatJsonSchema : IJsonModel { - InternalChatResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalChatResponseFormatJsonSchema() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalChatResponseFormatJsonSchema)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("json_schema") != true) + { + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); } + } + + InternalChatResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalChatResponseFormatJsonSchema)JsonModelCreateCore(ref reader, options); + protected override ChatResponseFormat 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(InternalChatResponseFormatJsonSchema)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement, options); } - internal static InternalChatResponseFormatJsonSchema DeserializeInternalChatResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatResponseFormatJsonSchema DeserializeInternalChatResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "json_schema"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("json_schema"u8)) + if (prop.NameEquals("type"u8)) { - jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("json_schema"u8)) { - type = property.Value.GetString(); + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + return new InternalChatResponseFormatJsonSchema(@type, additionalBinaryDataProperties, jsonSchema); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -72,15 +89,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - InternalChatResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalChatResponseFormatJsonSchema)PersistableModelCreateCore(data, options); + protected override ChatResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement, options); } default: @@ -90,15 +108,20 @@ InternalChatResponseFormatJsonSchema IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalChatResponseFormatJsonSchema FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatResponseFormatJsonSchema internalChatResponseFormatJsonSchema) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement); + if (internalChatResponseFormatJsonSchema == null) + { + return null; + } + return BinaryContent.Create(internalChatResponseFormatJsonSchema, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalChatResponseFormatJsonSchema(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatResponseFormatJsonSchema(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs b/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs index d519acb14..42c9a120f 100644 --- a/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs +++ b/src/Generated/Models/InternalChatResponseFormatJsonSchema.cs @@ -4,29 +4,25 @@ using System; using System.Collections.Generic; +using OpenAI; using OpenAI.Internal; namespace OpenAI.Chat { internal partial class InternalChatResponseFormatJsonSchema : ChatResponseFormat { - public InternalChatResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + public InternalChatResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base("json_schema") { Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); - Type = "json_schema"; JsonSchema = jsonSchema; } - internal InternalChatResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + internal InternalChatResponseFormatJsonSchema(string @type, IDictionary additionalBinaryDataProperties, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(@type, additionalBinaryDataProperties) { JsonSchema = jsonSchema; } - internal InternalChatResponseFormatJsonSchema() - { - } - public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; } } } diff --git a/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs b/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs index 6ab2655f8..2100a5dfd 100644 --- a/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs +++ b/src/Generated/Models/InternalChatResponseFormatText.Serialization.cs @@ -7,55 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalChatResponseFormatText : IJsonModel { - InternalChatResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalChatResponseFormatText)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + InternalChatResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalChatResponseFormatText)JsonModelCreateCore(ref reader, options); + + protected override ChatResponseFormat 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(InternalChatResponseFormatText)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalChatResponseFormatText(document.RootElement, options); } - internal static InternalChatResponseFormatText DeserializeInternalChatResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalChatResponseFormatText DeserializeInternalChatResponseFormatText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "text"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalChatResponseFormatText(type, serializedAdditionalRawData); + return new InternalChatResponseFormatText(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -65,15 +73,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - InternalChatResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalChatResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalChatResponseFormatText)PersistableModelCreateCore(data, options); + protected override ChatResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalChatResponseFormatText(document.RootElement, options); } default: @@ -83,15 +92,20 @@ InternalChatResponseFormatText IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalChatResponseFormatText FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalChatResponseFormatText internalChatResponseFormatText) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalChatResponseFormatText(document.RootElement); + if (internalChatResponseFormatText == null) + { + return null; + } + return BinaryContent.Create(internalChatResponseFormatText, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalChatResponseFormatText(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalChatResponseFormatText(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalChatResponseFormatText.cs b/src/Generated/Models/InternalChatResponseFormatText.cs index 49e7771f0..4705b5972 100644 --- a/src/Generated/Models/InternalChatResponseFormatText.cs +++ b/src/Generated/Models/InternalChatResponseFormatText.cs @@ -9,12 +9,11 @@ namespace OpenAI.Chat { internal partial class InternalChatResponseFormatText : ChatResponseFormat { - public InternalChatResponseFormatText() + public InternalChatResponseFormatText() : base("text") { - Type = "text"; } - internal InternalChatResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalChatResponseFormatText(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs b/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs index 30ee85a04..20bd2f55e 100644 --- a/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs +++ b/src/Generated/Models/InternalCompleteUploadRequest.Serialization.cs @@ -7,38 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { internal partial class InternalCompleteUploadRequest : IJsonModel { + internal InternalCompleteUploadRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCompleteUploadRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("part_ids") != true) + if (_additionalBinaryDataProperties?.ContainsKey("part_ids") != true) { writer.WritePropertyName("part_ids"u8); writer.WriteStartArray(); - foreach (var item in PartIds) + foreach (string item in PartIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("md5") != true && Optional.IsDefined(Md5)) + if (Optional.IsDefined(Md5) && _additionalBinaryDataProperties?.ContainsKey("md5") != true) { writer.WritePropertyName("md5"u8); writer.WriteStringValue(Md5); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,64 +70,67 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode #endif } } - writer.WriteEndObject(); } - InternalCompleteUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCompleteUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCompleteUploadRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCompleteUploadRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCompleteUploadRequest(document.RootElement, options); } - internal static InternalCompleteUploadRequest DeserializeInternalCompleteUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCompleteUploadRequest DeserializeInternalCompleteUploadRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList partIds = default; string md5 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("part_ids"u8)) + if (prop.NameEquals("part_ids"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } partIds = array; continue; } - if (property.NameEquals("md5"u8)) + if (prop.NameEquals("md5"u8)) { - md5 = property.Value.GetString(); + md5 = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCompleteUploadRequest(partIds, md5, serializedAdditionalRawData); + return new InternalCompleteUploadRequest(partIds, md5, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -122,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - InternalCompleteUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCompleteUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCompleteUploadRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCompleteUploadRequest(document.RootElement, options); } default: @@ -140,15 +159,20 @@ InternalCompleteUploadRequest IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCompleteUploadRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCompleteUploadRequest internalCompleteUploadRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCompleteUploadRequest(document.RootElement); + if (internalCompleteUploadRequest == null) + { + return null; + } + return BinaryContent.Create(internalCompleteUploadRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCompleteUploadRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCompleteUploadRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCompleteUploadRequest.cs b/src/Generated/Models/InternalCompleteUploadRequest.cs index 74d4d5346..509bbb123 100644 --- a/src/Generated/Models/InternalCompleteUploadRequest.cs +++ b/src/Generated/Models/InternalCompleteUploadRequest.cs @@ -5,12 +5,14 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.Files { internal partial class InternalCompleteUploadRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCompleteUploadRequest(IEnumerable partIds) { Argument.AssertNotNull(partIds, nameof(partIds)); @@ -18,18 +20,21 @@ public InternalCompleteUploadRequest(IEnumerable partIds) PartIds = partIds.ToList(); } - internal InternalCompleteUploadRequest(IList partIds, string md5, IDictionary serializedAdditionalRawData) + internal InternalCompleteUploadRequest(IList partIds, string md5, IDictionary additionalBinaryDataProperties) { PartIds = partIds; Md5 = md5; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCompleteUploadRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList PartIds { get; } + public string Md5 { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateAssistantRequestModel.cs b/src/Generated/Models/InternalCreateAssistantRequestModel.cs index dff777d4f..b92d51fc7 100644 --- a/src/Generated/Models/InternalCreateAssistantRequestModel.cs +++ b/src/Generated/Models/InternalCreateAssistantRequestModel.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalCreateAssistantRequestModel : IEquatable { private readonly string _value; - - public InternalCreateAssistantRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string Gpt4oValue = "gpt-4o"; private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; @@ -40,39 +35,73 @@ public InternalCreateAssistantRequestModel(string value) private const string Gpt35Turbo0125Value = "gpt-3.5-turbo-0125"; private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; + public InternalCreateAssistantRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateAssistantRequestModel Gpt4o { get; } = new InternalCreateAssistantRequestModel(Gpt4oValue); + public static InternalCreateAssistantRequestModel Gpt4o20240806 { get; } = new InternalCreateAssistantRequestModel(Gpt4o20240806Value); + public static InternalCreateAssistantRequestModel Gpt4o20240513 { get; } = new InternalCreateAssistantRequestModel(Gpt4o20240513Value); + public static InternalCreateAssistantRequestModel Gpt4oMini { get; } = new InternalCreateAssistantRequestModel(Gpt4oMiniValue); + public static InternalCreateAssistantRequestModel Gpt4oMini20240718 { get; } = new InternalCreateAssistantRequestModel(Gpt4oMini20240718Value); + public static InternalCreateAssistantRequestModel Gpt4Turbo { get; } = new InternalCreateAssistantRequestModel(Gpt4TurboValue); + public static InternalCreateAssistantRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateAssistantRequestModel(Gpt4Turbo20240409Value); + public static InternalCreateAssistantRequestModel Gpt40125Preview { get; } = new InternalCreateAssistantRequestModel(Gpt40125PreviewValue); + public static InternalCreateAssistantRequestModel Gpt4TurboPreview { get; } = new InternalCreateAssistantRequestModel(Gpt4TurboPreviewValue); + public static InternalCreateAssistantRequestModel Gpt41106Preview { get; } = new InternalCreateAssistantRequestModel(Gpt41106PreviewValue); + public static InternalCreateAssistantRequestModel Gpt4VisionPreview { get; } = new InternalCreateAssistantRequestModel(Gpt4VisionPreviewValue); + public static InternalCreateAssistantRequestModel Gpt4 { get; } = new InternalCreateAssistantRequestModel(Gpt4Value); + public static InternalCreateAssistantRequestModel Gpt40314 { get; } = new InternalCreateAssistantRequestModel(Gpt40314Value); + public static InternalCreateAssistantRequestModel Gpt40613 { get; } = new InternalCreateAssistantRequestModel(Gpt40613Value); + public static InternalCreateAssistantRequestModel Gpt432k { get; } = new InternalCreateAssistantRequestModel(Gpt432kValue); + public static InternalCreateAssistantRequestModel Gpt432k0314 { get; } = new InternalCreateAssistantRequestModel(Gpt432k0314Value); + public static InternalCreateAssistantRequestModel Gpt432k0613 { get; } = new InternalCreateAssistantRequestModel(Gpt432k0613Value); + public static InternalCreateAssistantRequestModel Gpt35Turbo { get; } = new InternalCreateAssistantRequestModel(Gpt35TurboValue); + public static InternalCreateAssistantRequestModel Gpt35Turbo16k { get; } = new InternalCreateAssistantRequestModel(Gpt35Turbo16kValue); + public static InternalCreateAssistantRequestModel Gpt35Turbo0613 { get; } = new InternalCreateAssistantRequestModel(Gpt35Turbo0613Value); + public static InternalCreateAssistantRequestModel Gpt35Turbo1106 { get; } = new InternalCreateAssistantRequestModel(Gpt35Turbo1106Value); + public static InternalCreateAssistantRequestModel Gpt35Turbo0125 { get; } = new InternalCreateAssistantRequestModel(Gpt35Turbo0125Value); + public static InternalCreateAssistantRequestModel Gpt35Turbo16k0613 { get; } = new InternalCreateAssistantRequestModel(Gpt35Turbo16k0613Value); + public static bool operator ==(InternalCreateAssistantRequestModel left, InternalCreateAssistantRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateAssistantRequestModel left, InternalCreateAssistantRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateAssistantRequestModel(string value) => new InternalCreateAssistantRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateAssistantRequestModel other && Equals(other); + public bool Equals(InternalCreateAssistantRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs b/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs index d21e16129..685addea4 100644 --- a/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs +++ b/src/Generated/Models/InternalCreateAssistantRequestToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalCreateAssistantRequestToolResources : IJsonModel< { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateAssistantRequestToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWrite #endif } } - writer.WriteEndObject(); } - InternalCreateAssistantRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateAssistantRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateAssistantRequestToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateAssistantRequestToolResources(document.RootElement, options); } - internal static InternalCreateAssistantRequestToolResources DeserializeInternalCreateAssistantRequestToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateAssistantRequestToolResources DeserializeInternalCreateAssistantRequestToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter = default; FileSearchToolResources fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalCreateAssistantRequestToolResourcesCodeInterpreter.DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalCreateAssistantRequestToolResourcesCodeInterpreter.DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(property.Value, options); + fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateAssistantRequestToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalCreateAssistantRequestToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write( } } - InternalCreateAssistantRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateAssistantRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateAssistantRequestToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateAssistantRequestToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalCreateAssistantRequestToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateAssistantRequestToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateAssistantRequestToolResources internalCreateAssistantRequestToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateAssistantRequestToolResources(document.RootElement); + if (internalCreateAssistantRequestToolResources == null) + { + return null; + } + return BinaryContent.Create(internalCreateAssistantRequestToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateAssistantRequestToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateAssistantRequestToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs b/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs index 3ac5aa737..0bdda1dc2 100644 --- a/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs +++ b/src/Generated/Models/InternalCreateAssistantRequestToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalCreateAssistantRequestToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateAssistantRequestToolResources() { } - internal InternalCreateAssistantRequestToolResources(InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateAssistantRequestToolResources(InternalCreateAssistantRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateAssistantRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } + public FileSearchToolResources FileSearch { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.Serialization.cs index ea159b987..36c62aac1 100644 --- a/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalCreateAssistantRequestToolResourcesCodeInterprete { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateAssistantRequestToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Writ #endif } } - writer.WriteEndObject(); } - InternalCreateAssistantRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateAssistantRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateAssistantRequestToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateAssistantRequestToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalCreateAssistantRequestToolResourcesCodeInterpreter DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateAssistantRequestToolResourcesCodeInterpreter DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateAssistantRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalCreateAssistantRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateAssistantRequestToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateAssistantRequestToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalCreateAssistantRequestToolResourcesCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateAssistantRequestToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateAssistantRequestToolResourcesCodeInterpreter internalCreateAssistantRequestToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(document.RootElement); + if (internalCreateAssistantRequestToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalCreateAssistantRequestToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateAssistantRequestToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateAssistantRequestToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.cs index ee042f14f..a3cfe8ed0 100644 --- a/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalCreateAssistantRequestToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalCreateAssistantRequestToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateAssistantRequestToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalCreateAssistantRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary serializedAdditionalRawData) + internal InternalCreateAssistantRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateBatchRequest.Serialization.cs b/src/Generated/Models/InternalCreateBatchRequest.Serialization.cs index 3fb6cc73d..a9487ca5d 100644 --- a/src/Generated/Models/InternalCreateBatchRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateBatchRequest.Serialization.cs @@ -7,36 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalCreateBatchRequest : IJsonModel { + internal InternalCreateBatchRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateBatchRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("input_file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_file_id") != true) { writer.WritePropertyName("input_file_id"u8); writer.WriteStringValue(InputFileId); } - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) + if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) { writer.WritePropertyName("endpoint"u8); writer.WriteStringValue(Endpoint.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("completion_window") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_window") != true) { writer.WritePropertyName("completion_window"u8); writer.WriteStringValue(CompletionWindow.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -45,18 +55,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -64,7 +79,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -73,25 +88,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - InternalCreateBatchRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateBatchRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateBatchRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateBatchRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateBatchRequest(document.RootElement, options); } - internal static InternalCreateBatchRequest DeserializeInternalCreateBatchRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateBatchRequest DeserializeInternalCreateBatchRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -99,54 +112,59 @@ internal static InternalCreateBatchRequest DeserializeInternalCreateBatchRequest string inputFileId = default; InternalCreateBatchRequestEndpoint endpoint = default; InternalBatchCompletionTimeframe completionWindow = default; - IReadOnlyDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary metadata = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("input_file_id"u8)) + if (prop.NameEquals("input_file_id"u8)) { - inputFileId = property.Value.GetString(); + inputFileId = prop.Value.GetString(); continue; } - if (property.NameEquals("endpoint"u8)) + if (prop.NameEquals("endpoint"u8)) { - endpoint = new InternalCreateBatchRequestEndpoint(property.Value.GetString()); + endpoint = new InternalCreateBatchRequestEndpoint(prop.Value.GetString()); continue; } - if (property.NameEquals("completion_window"u8)) + if (prop.NameEquals("completion_window"u8)) { - completionWindow = new InternalBatchCompletionTimeframe(property.Value.GetString()); + completionWindow = new InternalBatchCompletionTimeframe(prop.Value.GetString()); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateBatchRequest(inputFileId, endpoint, completionWindow, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new InternalCreateBatchRequest(inputFileId, endpoint, completionWindow, metadata ?? new ChangeTrackingDictionary(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -156,15 +174,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalCreateBatchRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateBatchRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateBatchRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateBatchRequest(document.RootElement, options); } default: @@ -174,15 +193,20 @@ InternalCreateBatchRequest IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateBatchRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateBatchRequest internalCreateBatchRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateBatchRequest(document.RootElement); + if (internalCreateBatchRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateBatchRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateBatchRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateBatchRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateBatchRequest.cs b/src/Generated/Models/InternalCreateBatchRequest.cs index 4b5db4d78..c66d2b434 100644 --- a/src/Generated/Models/InternalCreateBatchRequest.cs +++ b/src/Generated/Models/InternalCreateBatchRequest.cs @@ -4,38 +4,42 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalCreateBatchRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateBatchRequest(string inputFileId, InternalCreateBatchRequestEndpoint endpoint) { - Argument.AssertNotNull(inputFileId, nameof(inputFileId)); - InputFileId = inputFileId; Endpoint = endpoint; Metadata = new ChangeTrackingDictionary(); } - internal InternalCreateBatchRequest(string inputFileId, InternalCreateBatchRequestEndpoint endpoint, InternalBatchCompletionTimeframe completionWindow, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal InternalCreateBatchRequest(string inputFileId, InternalCreateBatchRequestEndpoint endpoint, InternalBatchCompletionTimeframe completionWindow, IDictionary metadata, IDictionary additionalBinaryDataProperties) { InputFileId = inputFileId; Endpoint = endpoint; CompletionWindow = completionWindow; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateBatchRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string InputFileId { get; } + public InternalCreateBatchRequestEndpoint Endpoint { get; } - public InternalBatchCompletionTimeframe CompletionWindow { get; } = InternalBatchCompletionTimeframe._24h; - public IReadOnlyDictionary Metadata { get; } + public InternalBatchCompletionTimeframe CompletionWindow { get; } = "24h"; + + public IDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateBatchRequestEndpoint.cs b/src/Generated/Models/InternalCreateBatchRequestEndpoint.cs index 9163b9de6..3ab4ffb5e 100644 --- a/src/Generated/Models/InternalCreateBatchRequestEndpoint.cs +++ b/src/Generated/Models/InternalCreateBatchRequestEndpoint.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalCreateBatchRequestEndpoint : IEquatable { private readonly string _value; + private const string V1ChatCompletionsValue = "/v1/chat/completions"; + private const string V1EmbeddingsValue = "/v1/embeddings"; public InternalCreateBatchRequestEndpoint(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string V1ChatCompletionsValue = "/v1/chat/completions"; - private const string V1EmbeddingsValue = "/v1/embeddings"; + _value = value; + } public static InternalCreateBatchRequestEndpoint V1ChatCompletions { get; } = new InternalCreateBatchRequestEndpoint(V1ChatCompletionsValue); + public static InternalCreateBatchRequestEndpoint V1Embeddings { get; } = new InternalCreateBatchRequestEndpoint(V1EmbeddingsValue); + public static bool operator ==(InternalCreateBatchRequestEndpoint left, InternalCreateBatchRequestEndpoint right) => left.Equals(right); + public static bool operator !=(InternalCreateBatchRequestEndpoint left, InternalCreateBatchRequestEndpoint right) => !left.Equals(right); + public static implicit operator InternalCreateBatchRequestEndpoint(string value) => new InternalCreateBatchRequestEndpoint(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateBatchRequestEndpoint other && Equals(other); + public bool Equals(InternalCreateBatchRequestEndpoint other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.Serialization.cs index a5999bf8d..327b4890c 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.Serialization.cs @@ -7,63 +7,73 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionFunctionResponse : IJsonModel { + internal InternalCreateChatCompletionFunctionResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionFunctionResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("choices") != true) + if (_additionalBinaryDataProperties?.ContainsKey("choices") != true) { writer.WritePropertyName("choices"u8); writer.WriteStartArray(); - foreach (var item in Choices) + foreach (InternalCreateChatCompletionFunctionResponseChoice item in Choices) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("created") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) { writer.WritePropertyName("created"u8); writer.WriteNumberValue(Created, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) + if (Optional.IsDefined(SystemFingerprint) && _additionalBinaryDataProperties?.ContainsKey("system_fingerprint") != true) { writer.WritePropertyName("system_fingerprint"u8); writer.WriteStringValue(SystemFingerprint); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true && Optional.IsDefined(Usage)) + if (Optional.IsDefined(Usage) && _additionalBinaryDataProperties?.ContainsKey("usage") != true) { writer.WritePropertyName("usage"u8); writer.WriteObjectValue(Usage, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -71,7 +81,7 @@ void IJsonModel.Write(Utf8JsonWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -80,91 +90,86 @@ void IJsonModel.Write(Utf8JsonWrit #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionFunctionResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionFunctionResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionFunctionResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionFunctionResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionFunctionResponse(document.RootElement, options); } - internal static InternalCreateChatCompletionFunctionResponse DeserializeInternalCreateChatCompletionFunctionResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionFunctionResponse DeserializeInternalCreateChatCompletionFunctionResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - IReadOnlyList choices = default; + IList choices = default; DateTimeOffset created = default; string model = default; string systemFingerprint = default; InternalCreateChatCompletionFunctionResponseObject @object = default; ChatTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("choices"u8)) + if (prop.NameEquals("choices"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalCreateChatCompletionFunctionResponseChoice.DeserializeInternalCreateChatCompletionFunctionResponseChoice(item, options)); } choices = array; continue; } - if (property.NameEquals("created"u8)) + if (prop.NameEquals("created"u8)) { - created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + created = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("system_fingerprint"u8)) + if (prop.NameEquals("system_fingerprint"u8)) { - systemFingerprint = property.Value.GetString(); + systemFingerprint = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalCreateChatCompletionFunctionResponseObject(property.Value.GetString()); + @object = new InternalCreateChatCompletionFunctionResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - usage = ChatTokenUsage.DeserializeChatTokenUsage(property.Value, options); + usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalCreateChatCompletionFunctionResponse( id, choices, @@ -173,13 +178,14 @@ internal static InternalCreateChatCompletionFunctionResponse DeserializeInternal systemFingerprint, @object, usage, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -189,15 +195,16 @@ BinaryData IPersistableModel.Write } } - InternalCreateChatCompletionFunctionResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionFunctionResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionFunctionResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionFunctionResponse(document.RootElement, options); } default: @@ -207,15 +214,20 @@ InternalCreateChatCompletionFunctionResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionFunctionResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionFunctionResponse internalCreateChatCompletionFunctionResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionFunctionResponse(document.RootElement); + if (internalCreateChatCompletionFunctionResponse == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionFunctionResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionFunctionResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionFunctionResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.cs index 19c621203..3f2b507f0 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponse.cs @@ -10,20 +10,17 @@ namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionFunctionResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionFunctionResponse(string id, IEnumerable choices, DateTimeOffset created, string model) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(choices, nameof(choices)); - Argument.AssertNotNull(model, nameof(model)); - Id = id; Choices = choices.ToList(); Created = created; Model = model; } - internal InternalCreateChatCompletionFunctionResponse(string id, IReadOnlyList choices, DateTimeOffset created, string model, string systemFingerprint, InternalCreateChatCompletionFunctionResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionFunctionResponse(string id, IList choices, DateTimeOffset created, string model, string systemFingerprint, InternalCreateChatCompletionFunctionResponseObject @object, ChatTokenUsage usage, IDictionary additionalBinaryDataProperties) { Id = id; Choices = choices; @@ -32,20 +29,27 @@ internal InternalCreateChatCompletionFunctionResponse(string id, IReadOnlyList Choices { get; } + + public IList Choices { get; } + public DateTimeOffset Created { get; } + public string Model { get; } + public string SystemFingerprint { get; } - public InternalCreateChatCompletionFunctionResponseObject Object { get; } = InternalCreateChatCompletionFunctionResponseObject.ChatCompletion; + + public InternalCreateChatCompletionFunctionResponseObject Object { get; } = "chat.completion"; public ChatTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.Serialization.cs index 55422fd8c..b4f1f585e 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionFunctionResponseChoice : IJsonModel { + internal InternalCreateChatCompletionFunctionResponseChoice() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionFunctionResponseChoice)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("finish_reason") != true) + if (_additionalBinaryDataProperties?.ContainsKey("finish_reason") != true) { writer.WritePropertyName("finish_reason"u8); writer.WriteStringValue(FinishReason.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteObjectValue(Message, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8Js } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,25 +65,23 @@ void IJsonModel.Write(Utf8Js #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionFunctionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionFunctionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionFunctionResponseChoice JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionFunctionResponseChoice)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionFunctionResponseChoice(document.RootElement, options); } - internal static InternalCreateChatCompletionFunctionResponseChoice DeserializeInternalCreateChatCompletionFunctionResponseChoice(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionFunctionResponseChoice DeserializeInternalCreateChatCompletionFunctionResponseChoice(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -81,39 +89,37 @@ internal static InternalCreateChatCompletionFunctionResponseChoice DeserializeIn InternalCreateChatCompletionFunctionResponseChoiceFinishReason finishReason = default; int index = default; InternalChatCompletionResponseMessage message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("finish_reason"u8)) + if (prop.NameEquals("finish_reason"u8)) { - finishReason = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(property.Value.GetString()); + finishReason = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(prop.Value.GetString()); continue; } - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = InternalChatCompletionResponseMessage.DeserializeInternalChatCompletionResponseMessage(property.Value, options); + message = InternalChatCompletionResponseMessage.DeserializeInternalChatCompletionResponseMessage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionFunctionResponseChoice(finishReason, index, message, serializedAdditionalRawData); + return new InternalCreateChatCompletionFunctionResponseChoice(finishReason, index, message, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel } } - InternalCreateChatCompletionFunctionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionFunctionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionFunctionResponseChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionFunctionResponseChoice(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalCreateChatCompletionFunctionResponseChoice IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionFunctionResponseChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionFunctionResponseChoice internalCreateChatCompletionFunctionResponseChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionFunctionResponseChoice(document.RootElement); + if (internalCreateChatCompletionFunctionResponseChoice == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionFunctionResponseChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionFunctionResponseChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionFunctionResponseChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.cs index 6e0687ded..f47f718ba 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoice.cs @@ -9,30 +9,33 @@ namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionFunctionResponseChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionFunctionResponseChoice(InternalCreateChatCompletionFunctionResponseChoiceFinishReason finishReason, int index, InternalChatCompletionResponseMessage message) { - Argument.AssertNotNull(message, nameof(message)); - FinishReason = finishReason; Index = index; Message = message; } - internal InternalCreateChatCompletionFunctionResponseChoice(InternalCreateChatCompletionFunctionResponseChoiceFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionFunctionResponseChoice(InternalCreateChatCompletionFunctionResponseChoiceFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, IDictionary additionalBinaryDataProperties) { FinishReason = finishReason; Index = index; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateChatCompletionFunctionResponseChoice() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateChatCompletionFunctionResponseChoiceFinishReason FinishReason { get; } + public int Index { get; } + public InternalChatCompletionResponseMessage Message { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoiceFinishReason.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoiceFinishReason.cs index 679edf97e..eee67eec1 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoiceFinishReason.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseChoiceFinishReason.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionFunctionResponseChoiceFinishReason : IEquatable { private readonly string _value; - - public InternalCreateChatCompletionFunctionResponseChoiceFinishReason(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string StopValue = "stop"; private const string LengthValue = "length"; private const string FunctionCallValue = "function_call"; private const string ContentFilterValue = "content_filter"; + public InternalCreateChatCompletionFunctionResponseChoiceFinishReason(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateChatCompletionFunctionResponseChoiceFinishReason Stop { get; } = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(StopValue); + public static InternalCreateChatCompletionFunctionResponseChoiceFinishReason Length { get; } = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(LengthValue); + public static InternalCreateChatCompletionFunctionResponseChoiceFinishReason FunctionCall { get; } = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(FunctionCallValue); + public static InternalCreateChatCompletionFunctionResponseChoiceFinishReason ContentFilter { get; } = new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(ContentFilterValue); + public static bool operator ==(InternalCreateChatCompletionFunctionResponseChoiceFinishReason left, InternalCreateChatCompletionFunctionResponseChoiceFinishReason right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionFunctionResponseChoiceFinishReason left, InternalCreateChatCompletionFunctionResponseChoiceFinishReason right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionFunctionResponseChoiceFinishReason(string value) => new InternalCreateChatCompletionFunctionResponseChoiceFinishReason(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionFunctionResponseChoiceFinishReason other && Equals(other); + public bool Equals(InternalCreateChatCompletionFunctionResponseChoiceFinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseObject.cs b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseObject.cs index 43c04df1d..67e58e465 100644 --- a/src/Generated/Models/InternalCreateChatCompletionFunctionResponseObject.cs +++ b/src/Generated/Models/InternalCreateChatCompletionFunctionResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionFunctionResponseObject : IEquatable { private readonly string _value; + private const string ChatCompletionValue = "chat.completion"; public InternalCreateChatCompletionFunctionResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ChatCompletionValue = "chat.completion"; + _value = value; + } public static InternalCreateChatCompletionFunctionResponseObject ChatCompletion { get; } = new InternalCreateChatCompletionFunctionResponseObject(ChatCompletionValue); + public static bool operator ==(InternalCreateChatCompletionFunctionResponseObject left, InternalCreateChatCompletionFunctionResponseObject right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionFunctionResponseObject left, InternalCreateChatCompletionFunctionResponseObject right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionFunctionResponseObject(string value) => new InternalCreateChatCompletionFunctionResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionFunctionResponseObject other && Equals(other); + public bool Equals(InternalCreateChatCompletionFunctionResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs b/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs index af6621119..f8e62d274 100644 --- a/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs +++ b/src/Generated/Models/InternalCreateChatCompletionRequestModel.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionRequestModel : IEquatable { private readonly string _value; - - public InternalCreateChatCompletionRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string O1PreviewValue = "o1-preview"; private const string O1Preview20240912Value = "o1-preview-2024-09-12"; private const string O1MiniValue = "o1-mini"; @@ -48,47 +43,89 @@ public InternalCreateChatCompletionRequestModel(string value) private const string Gpt35Turbo0125Value = "gpt-3.5-turbo-0125"; private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; + public InternalCreateChatCompletionRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateChatCompletionRequestModel O1Preview { get; } = new InternalCreateChatCompletionRequestModel(O1PreviewValue); + public static InternalCreateChatCompletionRequestModel O1Preview20240912 { get; } = new InternalCreateChatCompletionRequestModel(O1Preview20240912Value); + public static InternalCreateChatCompletionRequestModel O1Mini { get; } = new InternalCreateChatCompletionRequestModel(O1MiniValue); + public static InternalCreateChatCompletionRequestModel O1Mini20240912 { get; } = new InternalCreateChatCompletionRequestModel(O1Mini20240912Value); + public static InternalCreateChatCompletionRequestModel Gpt4o { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oValue); + public static InternalCreateChatCompletionRequestModel Gpt4o20240806 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4o20240806Value); + public static InternalCreateChatCompletionRequestModel Gpt4o20240513 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4o20240513Value); + public static InternalCreateChatCompletionRequestModel Gpt4oRealtimePreview { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oRealtimePreviewValue); + public static InternalCreateChatCompletionRequestModel Gpt4oRealtimePreview20241001 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oRealtimePreview20241001Value); + public static InternalCreateChatCompletionRequestModel Chatgpt4oLatest { get; } = new InternalCreateChatCompletionRequestModel(Chatgpt4oLatestValue); + public static InternalCreateChatCompletionRequestModel Gpt4oMini { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oMiniValue); + public static InternalCreateChatCompletionRequestModel Gpt4oMini20240718 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4oMini20240718Value); + public static InternalCreateChatCompletionRequestModel Gpt4Turbo { get; } = new InternalCreateChatCompletionRequestModel(Gpt4TurboValue); + public static InternalCreateChatCompletionRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4Turbo20240409Value); + public static InternalCreateChatCompletionRequestModel Gpt40125Preview { get; } = new InternalCreateChatCompletionRequestModel(Gpt40125PreviewValue); + public static InternalCreateChatCompletionRequestModel Gpt4TurboPreview { get; } = new InternalCreateChatCompletionRequestModel(Gpt4TurboPreviewValue); + public static InternalCreateChatCompletionRequestModel Gpt41106Preview { get; } = new InternalCreateChatCompletionRequestModel(Gpt41106PreviewValue); + public static InternalCreateChatCompletionRequestModel Gpt4VisionPreview { get; } = new InternalCreateChatCompletionRequestModel(Gpt4VisionPreviewValue); + public static InternalCreateChatCompletionRequestModel Gpt4 { get; } = new InternalCreateChatCompletionRequestModel(Gpt4Value); + public static InternalCreateChatCompletionRequestModel Gpt40314 { get; } = new InternalCreateChatCompletionRequestModel(Gpt40314Value); + public static InternalCreateChatCompletionRequestModel Gpt40613 { get; } = new InternalCreateChatCompletionRequestModel(Gpt40613Value); + public static InternalCreateChatCompletionRequestModel Gpt432k { get; } = new InternalCreateChatCompletionRequestModel(Gpt432kValue); + public static InternalCreateChatCompletionRequestModel Gpt432k0314 { get; } = new InternalCreateChatCompletionRequestModel(Gpt432k0314Value); + public static InternalCreateChatCompletionRequestModel Gpt432k0613 { get; } = new InternalCreateChatCompletionRequestModel(Gpt432k0613Value); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo { get; } = new InternalCreateChatCompletionRequestModel(Gpt35TurboValue); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo16k { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo16kValue); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo0301 { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo0301Value); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo0613 { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo0613Value); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo1106 { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo1106Value); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo0125 { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo0125Value); + public static InternalCreateChatCompletionRequestModel Gpt35Turbo16k0613 { get; } = new InternalCreateChatCompletionRequestModel(Gpt35Turbo16k0613Value); + public static bool operator ==(InternalCreateChatCompletionRequestModel left, InternalCreateChatCompletionRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionRequestModel left, InternalCreateChatCompletionRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionRequestModel(string value) => new InternalCreateChatCompletionRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionRequestModel other && Equals(other); + public bool Equals(InternalCreateChatCompletionRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs b/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs index 7d6f7f657..17221cfbe 100644 --- a/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs +++ b/src/Generated/Models/InternalCreateChatCompletionRequestServiceTier.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionRequestServiceTier : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string DefaultValue = "default"; public InternalCreateChatCompletionRequestServiceTier(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string DefaultValue = "default"; + _value = value; + } public static InternalCreateChatCompletionRequestServiceTier Auto { get; } = new InternalCreateChatCompletionRequestServiceTier(AutoValue); + public static InternalCreateChatCompletionRequestServiceTier Default { get; } = new InternalCreateChatCompletionRequestServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionRequestServiceTier left, InternalCreateChatCompletionRequestServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionRequestServiceTier left, InternalCreateChatCompletionRequestServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionRequestServiceTier(string value) => new InternalCreateChatCompletionRequestServiceTier(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionRequestServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionRequestServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionRequestToolChoice.cs b/src/Generated/Models/InternalCreateChatCompletionRequestToolChoice.cs index 04328dced..dbbe528ee 100644 --- a/src/Generated/Models/InternalCreateChatCompletionRequestToolChoice.cs +++ b/src/Generated/Models/InternalCreateChatCompletionRequestToolChoice.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionRequestToolChoice : IEquatable { private readonly string _value; + private const string NoneValue = "none"; + private const string AutoValue = "auto"; + private const string RequiredValue = "required"; public InternalCreateChatCompletionRequestToolChoice(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string NoneValue = "none"; - private const string AutoValue = "auto"; - private const string RequiredValue = "required"; + _value = value; + } public static InternalCreateChatCompletionRequestToolChoice None { get; } = new InternalCreateChatCompletionRequestToolChoice(NoneValue); + public static InternalCreateChatCompletionRequestToolChoice Auto { get; } = new InternalCreateChatCompletionRequestToolChoice(AutoValue); + public static InternalCreateChatCompletionRequestToolChoice Required { get; } = new InternalCreateChatCompletionRequestToolChoice(RequiredValue); + public static bool operator ==(InternalCreateChatCompletionRequestToolChoice left, InternalCreateChatCompletionRequestToolChoice right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionRequestToolChoice left, InternalCreateChatCompletionRequestToolChoice right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionRequestToolChoice(string value) => new InternalCreateChatCompletionRequestToolChoice(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionRequestToolChoice other && Equals(other); + public bool Equals(InternalCreateChatCompletionRequestToolChoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseChoice.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionResponseChoice.Serialization.cs index dc72c0a83..69403c77f 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseChoice.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseChoice.Serialization.cs @@ -7,36 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionResponseChoice : IJsonModel { + internal InternalCreateChatCompletionResponseChoice() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionResponseChoice)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("finish_reason") != true) + if (_additionalBinaryDataProperties?.ContainsKey("finish_reason") != true) { writer.WritePropertyName("finish_reason"u8); writer.WriteStringValue(FinishReason.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteObjectValue(Message, options); } - if (SerializedAdditionalRawData?.ContainsKey("logprobs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("logprobs") != true) { if (Logprobs != null) { @@ -45,12 +55,12 @@ void IJsonModel.Write(Utf8JsonWriter } else { - writer.WriteNull("logprobs"); + writer.WriteNull("logprobs"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -58,7 +68,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -67,76 +77,72 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionResponseChoice JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionResponseChoice)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionResponseChoice(document.RootElement, options); } - internal static InternalCreateChatCompletionResponseChoice DeserializeInternalCreateChatCompletionResponseChoice(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionResponseChoice DeserializeInternalCreateChatCompletionResponseChoice(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ChatFinishReason finishReason = default; + Chat.ChatFinishReason finishReason = default; int index = default; InternalChatCompletionResponseMessage message = default; InternalCreateChatCompletionResponseChoiceLogprobs logprobs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("finish_reason"u8)) + if (prop.NameEquals("finish_reason"u8)) { - finishReason = property.Value.GetString().ToChatFinishReason(); + finishReason = prop.Value.GetString().ToChatFinishReason(); continue; } - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = InternalChatCompletionResponseMessage.DeserializeInternalChatCompletionResponseMessage(property.Value, options); + message = InternalChatCompletionResponseMessage.DeserializeInternalChatCompletionResponseMessage(prop.Value, options); continue; } - if (property.NameEquals("logprobs"u8)) + if (prop.NameEquals("logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { logprobs = null; continue; } - logprobs = InternalCreateChatCompletionResponseChoiceLogprobs.DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(property.Value, options); + logprobs = InternalCreateChatCompletionResponseChoiceLogprobs.DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionResponseChoice(finishReason, index, message, logprobs, serializedAdditionalRawData); + return new InternalCreateChatCompletionResponseChoice(finishReason, index, message, logprobs, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -146,15 +152,16 @@ BinaryData IPersistableModel.Write(M } } - InternalCreateChatCompletionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionResponseChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionResponseChoice(document.RootElement, options); } default: @@ -164,15 +171,20 @@ InternalCreateChatCompletionResponseChoice IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionResponseChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionResponseChoice internalCreateChatCompletionResponseChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionResponseChoice(document.RootElement); + if (internalCreateChatCompletionResponseChoice == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionResponseChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionResponseChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionResponseChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseChoice.cs b/src/Generated/Models/InternalCreateChatCompletionResponseChoice.cs index 88a8051cf..42878f48b 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseChoice.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseChoice.cs @@ -9,33 +9,37 @@ namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionResponseChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalCreateChatCompletionResponseChoice(ChatFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, InternalCreateChatCompletionResponseChoiceLogprobs logprobs) - { - Argument.AssertNotNull(message, nameof(message)); + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionResponseChoice(Chat.ChatFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, InternalCreateChatCompletionResponseChoiceLogprobs logprobs) + { FinishReason = finishReason; Index = index; Message = message; Logprobs = logprobs; } - internal InternalCreateChatCompletionResponseChoice(ChatFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, InternalCreateChatCompletionResponseChoiceLogprobs logprobs, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionResponseChoice(Chat.ChatFinishReason finishReason, int index, InternalChatCompletionResponseMessage message, InternalCreateChatCompletionResponseChoiceLogprobs logprobs, IDictionary additionalBinaryDataProperties) { FinishReason = finishReason; Index = index; Message = message; Logprobs = logprobs; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateChatCompletionResponseChoice() - { - } + public Chat.ChatFinishReason FinishReason { get; } - public ChatFinishReason FinishReason { get; } public int Index { get; } + public InternalChatCompletionResponseMessage Message { get; } + public InternalCreateChatCompletionResponseChoiceLogprobs Logprobs { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs index 990bd4a03..f7bb85157 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,20 +15,25 @@ internal partial class InternalCreateChatCompletionResponseChoiceLogprobs : IJso { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionResponseChoiceLogprobs)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("content") != true) { if (Content != null && Optional.IsCollectionDefined(Content)) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ChatTokenLogProbabilityDetails item in Content) { writer.WriteObjectValue(item, options); } @@ -35,16 +41,16 @@ void IJsonModel.Write(Utf8Js } else { - writer.WriteNull("content"); + writer.WriteNull("content"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("refusal") != true) { if (Refusal != null && Optional.IsCollectionDefined(Refusal)) { writer.WritePropertyName("refusal"u8); writer.WriteStartArray(); - foreach (var item in Refusal) + foreach (ChatTokenLogProbabilityDetails item in Refusal) { writer.WriteObjectValue(item, options); } @@ -52,12 +58,12 @@ void IJsonModel.Write(Utf8Js } else { - writer.WriteNull("refusal"); + writer.WriteNull("refusal"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +71,7 @@ void IJsonModel.Write(Utf8Js } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,59 +80,56 @@ void IJsonModel.Write(Utf8Js #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionResponseChoiceLogprobs JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionResponseChoiceLogprobs)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(document.RootElement, options); } - internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList content = default; IReadOnlyList refusal = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("content"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { content = new ChangeTrackingList(); continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTokenLogProbabilityDetails.DeserializeChatTokenLogProbabilityDetails(item, options)); } content = array; continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("refusal"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { refusal = new ChangeTrackingList(); continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTokenLogProbabilityDetails.DeserializeChatTokenLogProbabilityDetails(item, options)); } @@ -135,18 +138,17 @@ internal static InternalCreateChatCompletionResponseChoiceLogprobs DeserializeIn } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionResponseChoiceLogprobs(content, refusal, serializedAdditionalRawData); + return new InternalCreateChatCompletionResponseChoiceLogprobs(content, refusal, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -156,15 +158,16 @@ BinaryData IPersistableModel } } - InternalCreateChatCompletionResponseChoiceLogprobs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionResponseChoiceLogprobs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionResponseChoiceLogprobs 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(document.RootElement, options); } default: @@ -174,15 +177,20 @@ InternalCreateChatCompletionResponseChoiceLogprobs IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionResponseChoiceLogprobs FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionResponseChoiceLogprobs internalCreateChatCompletionResponseChoiceLogprobs) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(document.RootElement); + if (internalCreateChatCompletionResponseChoiceLogprobs == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionResponseChoiceLogprobs, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionResponseChoiceLogprobs(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionResponseChoiceLogprobs(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs b/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs index 2dc90fd32..33eb44cde 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseChoiceLogprobs.cs @@ -4,26 +4,35 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionResponseChoiceLogprobs { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionResponseChoiceLogprobs() { Content = new ChangeTrackingList(); Refusal = new ChangeTrackingList(); } - internal InternalCreateChatCompletionResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary additionalBinaryDataProperties) { Content = content; Refusal = refusal; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IReadOnlyList Content { get; } + public IReadOnlyList Refusal { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseObject.cs b/src/Generated/Models/InternalCreateChatCompletionResponseObject.cs index 9c1c590ed..2ec8db01b 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseObject.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionResponseObject : IEquatable { private readonly string _value; + private const string ChatCompletionValue = "chat.completion"; public InternalCreateChatCompletionResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ChatCompletionValue = "chat.completion"; + _value = value; + } public static InternalCreateChatCompletionResponseObject ChatCompletion { get; } = new InternalCreateChatCompletionResponseObject(ChatCompletionValue); + public static bool operator ==(InternalCreateChatCompletionResponseObject left, InternalCreateChatCompletionResponseObject right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionResponseObject left, InternalCreateChatCompletionResponseObject right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionResponseObject(string value) => new InternalCreateChatCompletionResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionResponseObject other && Equals(other); + public bool Equals(InternalCreateChatCompletionResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs b/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs index 599297be0..e554b9485 100644 --- a/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs +++ b/src/Generated/Models/InternalCreateChatCompletionResponseServiceTier.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionResponseServiceTier : IEquatable { private readonly string _value; + private const string ScaleValue = "scale"; + private const string DefaultValue = "default"; public InternalCreateChatCompletionResponseServiceTier(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ScaleValue = "scale"; - private const string DefaultValue = "default"; + _value = value; + } public static InternalCreateChatCompletionResponseServiceTier Scale { get; } = new InternalCreateChatCompletionResponseServiceTier(ScaleValue); + public static InternalCreateChatCompletionResponseServiceTier Default { get; } = new InternalCreateChatCompletionResponseServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionResponseServiceTier left, InternalCreateChatCompletionResponseServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionResponseServiceTier left, InternalCreateChatCompletionResponseServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionResponseServiceTier(string value) => new InternalCreateChatCompletionResponseServiceTier(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionResponseServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionResponseServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs index fd1dd8a10..62624c359 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.Serialization.cs @@ -6,27 +6,96 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionStreamResponseChoice : IJsonModel { - InternalCreateChatCompletionStreamResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalCreateChatCompletionStreamResponseChoice() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalCreateChatCompletionStreamResponseChoice)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalCreateChatCompletionStreamResponseChoice)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) + { + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(Delta, options); + } + if (Optional.IsDefined(Logprobs) && _additionalBinaryDataProperties?.ContainsKey("logprobs") != true) + { + if (Logprobs != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteObjectValue(Logprobs, options); + } + else + { + writer.WriteNull("logprobs"u8); + } } + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) + { + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + } + if (_additionalBinaryDataProperties?.ContainsKey("finish_reason") != true) + { + if (FinishReason != null) + { + writer.WritePropertyName("finish_reason"u8); + writer.WriteStringValue(FinishReason.Value.ToSerialString()); + } + else + { + writer.WriteNull("finishReason"u8); + } + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + InternalCreateChatCompletionStreamResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual InternalCreateChatCompletionStreamResponseChoice 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(InternalCreateChatCompletionStreamResponseChoice)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement, options); + return InternalCreateChatCompletionStreamResponseChoice.DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +105,17 @@ BinaryData IPersistableModel.W } } - InternalCreateChatCompletionStreamResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionStreamResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionStreamResponseChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement, options); + return InternalCreateChatCompletionStreamResponseChoice.DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement, options); } default: throw new FormatException($"The model {nameof(InternalCreateChatCompletionStreamResponseChoice)} does not support reading '{options.Format}' format."); @@ -54,15 +124,20 @@ InternalCreateChatCompletionStreamResponseChoice IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionStreamResponseChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionStreamResponseChoice internalCreateChatCompletionStreamResponseChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement); + if (internalCreateChatCompletionStreamResponseChoice == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionStreamResponseChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionStreamResponseChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return InternalCreateChatCompletionStreamResponseChoice.DeserializeInternalCreateChatCompletionStreamResponseChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.cs index 6bb376d9f..c81fe2ab0 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoice.cs @@ -9,31 +9,34 @@ namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionStreamResponseChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalCreateChatCompletionStreamResponseChoice(InternalChatCompletionStreamResponseDelta delta, ChatFinishReason? finishReason, int index) - { - Argument.AssertNotNull(delta, nameof(delta)); + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionStreamResponseChoice(InternalChatCompletionStreamResponseDelta delta, int index, Chat.ChatFinishReason? finishReason) + { Delta = delta; - FinishReason = finishReason; Index = index; + FinishReason = finishReason; } - internal InternalCreateChatCompletionStreamResponseChoice(InternalChatCompletionStreamResponseDelta delta, InternalCreateChatCompletionStreamResponseChoiceLogprobs logprobs, ChatFinishReason? finishReason, int index, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionStreamResponseChoice(InternalChatCompletionStreamResponseDelta delta, InternalCreateChatCompletionStreamResponseChoiceLogprobs logprobs, int index, Chat.ChatFinishReason? finishReason, IDictionary additionalBinaryDataProperties) { Delta = delta; Logprobs = logprobs; - FinishReason = finishReason; Index = index; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateChatCompletionStreamResponseChoice() - { + FinishReason = finishReason; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalChatCompletionStreamResponseDelta Delta { get; } + public InternalCreateChatCompletionStreamResponseChoiceLogprobs Logprobs { get; } + public int Index { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceFinishReason.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceFinishReason.cs index 76fdf5a27..deec1998c 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceFinishReason.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceFinishReason.cs @@ -4,39 +4,50 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionStreamResponseChoiceFinishReason : IEquatable { private readonly string _value; - - public InternalCreateChatCompletionStreamResponseChoiceFinishReason(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string StopValue = "stop"; private const string LengthValue = "length"; private const string ToolCallsValue = "tool_calls"; private const string ContentFilterValue = "content_filter"; private const string FunctionCallValue = "function_call"; + public InternalCreateChatCompletionStreamResponseChoiceFinishReason(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateChatCompletionStreamResponseChoiceFinishReason Stop { get; } = new InternalCreateChatCompletionStreamResponseChoiceFinishReason(StopValue); + public static InternalCreateChatCompletionStreamResponseChoiceFinishReason Length { get; } = new InternalCreateChatCompletionStreamResponseChoiceFinishReason(LengthValue); + public static InternalCreateChatCompletionStreamResponseChoiceFinishReason ToolCalls { get; } = new InternalCreateChatCompletionStreamResponseChoiceFinishReason(ToolCallsValue); + public static InternalCreateChatCompletionStreamResponseChoiceFinishReason ContentFilter { get; } = new InternalCreateChatCompletionStreamResponseChoiceFinishReason(ContentFilterValue); + public static InternalCreateChatCompletionStreamResponseChoiceFinishReason FunctionCall { get; } = new InternalCreateChatCompletionStreamResponseChoiceFinishReason(FunctionCallValue); + public static bool operator ==(InternalCreateChatCompletionStreamResponseChoiceFinishReason left, InternalCreateChatCompletionStreamResponseChoiceFinishReason right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionStreamResponseChoiceFinishReason left, InternalCreateChatCompletionStreamResponseChoiceFinishReason right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionStreamResponseChoiceFinishReason(string value) => new InternalCreateChatCompletionStreamResponseChoiceFinishReason(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionStreamResponseChoiceFinishReason other && Equals(other); + public bool Equals(InternalCreateChatCompletionStreamResponseChoiceFinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs index 15787f4fb..4c7d91664 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,20 +15,25 @@ internal partial class InternalCreateChatCompletionStreamResponseChoiceLogprobs { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionStreamResponseChoiceLogprobs)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("content") != true) { if (Content != null && Optional.IsCollectionDefined(Content)) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ChatTokenLogProbabilityDetails item in Content) { writer.WriteObjectValue(item, options); } @@ -35,16 +41,16 @@ void IJsonModel.Write( } else { - writer.WriteNull("content"); + writer.WriteNull("content"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("refusal") != true) { if (Refusal != null && Optional.IsCollectionDefined(Refusal)) { writer.WritePropertyName("refusal"u8); writer.WriteStartArray(); - foreach (var item in Refusal) + foreach (ChatTokenLogProbabilityDetails item in Refusal) { writer.WriteObjectValue(item, options); } @@ -52,12 +58,12 @@ void IJsonModel.Write( } else { - writer.WriteNull("refusal"); + writer.WriteNull("refusal"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +71,7 @@ void IJsonModel.Write( } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,59 +80,56 @@ void IJsonModel.Write( #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionStreamResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionStreamResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionStreamResponseChoiceLogprobs JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionStreamResponseChoiceLogprobs)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(document.RootElement, options); } - internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList content = default; IReadOnlyList refusal = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("content"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { content = new ChangeTrackingList(); continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTokenLogProbabilityDetails.DeserializeChatTokenLogProbabilityDetails(item, options)); } content = array; continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("refusal"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { refusal = new ChangeTrackingList(); continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTokenLogProbabilityDetails.DeserializeChatTokenLogProbabilityDetails(item, options)); } @@ -135,18 +138,17 @@ internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs Deseria } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionStreamResponseChoiceLogprobs(content, refusal, serializedAdditionalRawData); + return new InternalCreateChatCompletionStreamResponseChoiceLogprobs(content, refusal, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -156,15 +158,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionStreamResponseChoiceLogprobs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionStreamResponseChoiceLogprobs 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(document.RootElement, options); } default: @@ -174,15 +177,20 @@ InternalCreateChatCompletionStreamResponseChoiceLogprobs IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionStreamResponseChoiceLogprobs FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionStreamResponseChoiceLogprobs internalCreateChatCompletionStreamResponseChoiceLogprobs) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(document.RootElement); + if (internalCreateChatCompletionStreamResponseChoiceLogprobs == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionStreamResponseChoiceLogprobs, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionStreamResponseChoiceLogprobs(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionStreamResponseChoiceLogprobs(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs index 5493f1d50..58c6b0aee 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseChoiceLogprobs.cs @@ -4,26 +4,35 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionStreamResponseChoiceLogprobs { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionStreamResponseChoiceLogprobs() { Content = new ChangeTrackingList(); Refusal = new ChangeTrackingList(); } - internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionStreamResponseChoiceLogprobs(IReadOnlyList content, IReadOnlyList refusal, IDictionary additionalBinaryDataProperties) { Content = content; Refusal = refusal; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IReadOnlyList Content { get; } + public IReadOnlyList Refusal { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseObject.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseObject.cs index 65aca720e..dd74ac7ff 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseObject.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionStreamResponseObject : IEquatable { private readonly string _value; + private const string ChatCompletionChunkValue = "chat.completion.chunk"; public InternalCreateChatCompletionStreamResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ChatCompletionChunkValue = "chat.completion.chunk"; + _value = value; + } public static InternalCreateChatCompletionStreamResponseObject ChatCompletionChunk { get; } = new InternalCreateChatCompletionStreamResponseObject(ChatCompletionChunkValue); + public static bool operator ==(InternalCreateChatCompletionStreamResponseObject left, InternalCreateChatCompletionStreamResponseObject right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionStreamResponseObject left, InternalCreateChatCompletionStreamResponseObject right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionStreamResponseObject(string value) => new InternalCreateChatCompletionStreamResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionStreamResponseObject other && Equals(other); + public bool Equals(InternalCreateChatCompletionStreamResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs index 0f2eb1326..b7c915064 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseServiceTier.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Chat { internal readonly partial struct InternalCreateChatCompletionStreamResponseServiceTier : IEquatable { private readonly string _value; + private const string ScaleValue = "scale"; + private const string DefaultValue = "default"; public InternalCreateChatCompletionStreamResponseServiceTier(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ScaleValue = "scale"; - private const string DefaultValue = "default"; + _value = value; + } public static InternalCreateChatCompletionStreamResponseServiceTier Scale { get; } = new InternalCreateChatCompletionStreamResponseServiceTier(ScaleValue); + public static InternalCreateChatCompletionStreamResponseServiceTier Default { get; } = new InternalCreateChatCompletionStreamResponseServiceTier(DefaultValue); + public static bool operator ==(InternalCreateChatCompletionStreamResponseServiceTier left, InternalCreateChatCompletionStreamResponseServiceTier right) => left.Equals(right); + public static bool operator !=(InternalCreateChatCompletionStreamResponseServiceTier left, InternalCreateChatCompletionStreamResponseServiceTier right) => !left.Equals(right); + public static implicit operator InternalCreateChatCompletionStreamResponseServiceTier(string value) => new InternalCreateChatCompletionStreamResponseServiceTier(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateChatCompletionStreamResponseServiceTier other && Equals(other); + public bool Equals(InternalCreateChatCompletionStreamResponseServiceTier other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.Serialization.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.Serialization.cs index 300a01f0c..2729b9e7c 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.Serialization.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionStreamResponseUsage : IJsonModel { + internal InternalCreateChatCompletionStreamResponseUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateChatCompletionStreamResponseUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("completion_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_tokens") != true) { writer.WritePropertyName("completion_tokens"u8); writer.WriteNumberValue(CompletionTokens); } - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); writer.WriteNumberValue(PromptTokens); } - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokens); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,25 +65,23 @@ void IJsonModel.Write(Utf8JsonW #endif } } - writer.WriteEndObject(); } - InternalCreateChatCompletionStreamResponseUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateChatCompletionStreamResponseUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateChatCompletionStreamResponseUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateChatCompletionStreamResponseUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateChatCompletionStreamResponseUsage(document.RootElement, options); } - internal static InternalCreateChatCompletionStreamResponseUsage DeserializeInternalCreateChatCompletionStreamResponseUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateChatCompletionStreamResponseUsage DeserializeInternalCreateChatCompletionStreamResponseUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -81,39 +89,37 @@ internal static InternalCreateChatCompletionStreamResponseUsage DeserializeInter int completionTokens = default; int promptTokens = default; int totalTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("completion_tokens"u8)) + if (prop.NameEquals("completion_tokens"u8)) { - completionTokens = property.Value.GetInt32(); + completionTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("prompt_tokens"u8)) + if (prop.NameEquals("prompt_tokens"u8)) { - promptTokens = property.Value.GetInt32(); + promptTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokens = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateChatCompletionStreamResponseUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + return new InternalCreateChatCompletionStreamResponseUsage(completionTokens, promptTokens, totalTokens, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Wr } } - InternalCreateChatCompletionStreamResponseUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateChatCompletionStreamResponseUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateChatCompletionStreamResponseUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateChatCompletionStreamResponseUsage(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalCreateChatCompletionStreamResponseUsage IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateChatCompletionStreamResponseUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateChatCompletionStreamResponseUsage internalCreateChatCompletionStreamResponseUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateChatCompletionStreamResponseUsage(document.RootElement); + if (internalCreateChatCompletionStreamResponseUsage == null) + { + return null; + } + return BinaryContent.Create(internalCreateChatCompletionStreamResponseUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateChatCompletionStreamResponseUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateChatCompletionStreamResponseUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.cs b/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.cs index 922ce4cae..3618fba02 100644 --- a/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.cs +++ b/src/Generated/Models/InternalCreateChatCompletionStreamResponseUsage.cs @@ -9,7 +9,8 @@ namespace OpenAI.Chat { internal partial class InternalCreateChatCompletionStreamResponseUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateChatCompletionStreamResponseUsage(int completionTokens, int promptTokens, int totalTokens) { CompletionTokens = completionTokens; @@ -17,20 +18,24 @@ internal InternalCreateChatCompletionStreamResponseUsage(int completionTokens, i TotalTokens = totalTokens; } - internal InternalCreateChatCompletionStreamResponseUsage(int completionTokens, int promptTokens, int totalTokens, IDictionary serializedAdditionalRawData) + internal InternalCreateChatCompletionStreamResponseUsage(int completionTokens, int promptTokens, int totalTokens, IDictionary additionalBinaryDataProperties) { CompletionTokens = completionTokens; PromptTokens = promptTokens; TotalTokens = totalTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateChatCompletionStreamResponseUsage() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int CompletionTokens { get; } + public int PromptTokens { get; } + public int TotalTokens { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateCompletionRequest.Serialization.cs b/src/Generated/Models/InternalCreateCompletionRequest.Serialization.cs index 6658d5c48..ea5ce997e 100644 --- a/src/Generated/Models/InternalCreateCompletionRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateCompletionRequest.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Chat; namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionRequest : IJsonModel { + internal InternalCreateCompletionRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateCompletionRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt") != true) { if (Prompt != null) { writer.WritePropertyName("prompt"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(Prompt); + writer.WriteRawValue(Prompt); #else using (JsonDocument document = JsonDocument.Parse(Prompt)) { @@ -43,10 +53,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("prompt"); + writer.WriteNull("prompt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("best_of") != true && Optional.IsDefined(BestOf)) + if (Optional.IsDefined(BestOf) && _additionalBinaryDataProperties?.ContainsKey("best_of") != true) { if (BestOf != null) { @@ -55,10 +65,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("best_of"); + writer.WriteNull("bestOf"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("echo") != true && Optional.IsDefined(Echo)) + if (Optional.IsDefined(Echo) && _additionalBinaryDataProperties?.ContainsKey("echo") != true) { if (Echo != null) { @@ -67,10 +77,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("echo"); + writer.WriteNull("echo"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("frequency_penalty") != true && Optional.IsDefined(FrequencyPenalty)) + if (Optional.IsDefined(FrequencyPenalty) && _additionalBinaryDataProperties?.ContainsKey("frequency_penalty") != true) { if (FrequencyPenalty != null) { @@ -79,10 +89,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("frequency_penalty"); + writer.WriteNull("frequencyPenalty"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("logit_bias") != true && Optional.IsCollectionDefined(LogitBias)) + if (Optional.IsCollectionDefined(LogitBias) && _additionalBinaryDataProperties?.ContainsKey("logit_bias") != true) { if (LogitBias != null) { @@ -97,10 +107,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("logit_bias"); + writer.WriteNull("logitBias"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("logprobs") != true && Optional.IsDefined(Logprobs)) + if (Optional.IsDefined(Logprobs) && _additionalBinaryDataProperties?.ContainsKey("logprobs") != true) { if (Logprobs != null) { @@ -109,10 +119,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("logprobs"); + writer.WriteNull("logprobs"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_tokens") != true && Optional.IsDefined(MaxTokens)) + if (Optional.IsDefined(MaxTokens) && _additionalBinaryDataProperties?.ContainsKey("max_tokens") != true) { if (MaxTokens != null) { @@ -121,10 +131,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("max_tokens"); + writer.WriteNull("maxTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("n") != true && Optional.IsDefined(N)) + if (Optional.IsDefined(N) && _additionalBinaryDataProperties?.ContainsKey("n") != true) { if (N != null) { @@ -133,10 +143,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("n"); + writer.WriteNull("n"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("presence_penalty") != true && Optional.IsDefined(PresencePenalty)) + if (Optional.IsDefined(PresencePenalty) && _additionalBinaryDataProperties?.ContainsKey("presence_penalty") != true) { if (PresencePenalty != null) { @@ -145,10 +155,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("presence_penalty"); + writer.WriteNull("presencePenalty"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("seed") != true && Optional.IsDefined(Seed)) + if (Optional.IsDefined(Seed) && _additionalBinaryDataProperties?.ContainsKey("seed") != true) { if (Seed != null) { @@ -157,16 +167,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("seed"); + writer.WriteNull("seed"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stop") != true && Optional.IsDefined(Stop)) + if (Optional.IsDefined(Stop) && _additionalBinaryDataProperties?.ContainsKey("stop") != true) { if (Stop != null) { writer.WritePropertyName("stop"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(Stop); + writer.WriteRawValue(Stop); #else using (JsonDocument document = JsonDocument.Parse(Stop)) { @@ -176,10 +186,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("stop"); + writer.WriteNull("stop"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stream") != true && Optional.IsDefined(Stream)) + if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true) { if (Stream != null) { @@ -188,10 +198,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("stream"); + writer.WriteNull("stream"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stream_options") != true && Optional.IsDefined(StreamOptions)) + if (Optional.IsDefined(StreamOptions) && _additionalBinaryDataProperties?.ContainsKey("stream_options") != true) { if (StreamOptions != null) { @@ -200,10 +210,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("stream_options"); + writer.WriteNull("streamOptions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("suffix") != true && Optional.IsDefined(Suffix)) + if (Optional.IsDefined(Suffix) && _additionalBinaryDataProperties?.ContainsKey("suffix") != true) { if (Suffix != null) { @@ -212,10 +222,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("suffix"); + writer.WriteNull("suffix"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -224,10 +234,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(TopP)) + if (Optional.IsDefined(TopP) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { if (TopP != null) { @@ -236,17 +246,17 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("top_p"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(User)) + if (Optional.IsDefined(User) && _additionalBinaryDataProperties?.ContainsKey("user") != true) { writer.WritePropertyName("user"u8); writer.WriteStringValue(User); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -254,7 +264,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -263,25 +273,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalCreateCompletionRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateCompletionRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateCompletionRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateCompletionRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateCompletionRequest(document.RootElement, options); } - internal static InternalCreateCompletionRequest DeserializeInternalCreateCompletionRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateCompletionRequest DeserializeInternalCreateCompletionRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -304,191 +312,188 @@ internal static InternalCreateCompletionRequest DeserializeInternalCreateComplet float? temperature = default; float? topP = default; string user = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = new InternalCreateCompletionRequestModel(property.Value.GetString()); + model = new InternalCreateCompletionRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("prompt"u8)) + if (prop.NameEquals("prompt"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { prompt = null; continue; } - prompt = BinaryData.FromString(property.Value.GetRawText()); + prompt = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("best_of"u8)) + if (prop.NameEquals("best_of"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { bestOf = null; continue; } - bestOf = property.Value.GetInt32(); + bestOf = prop.Value.GetInt32(); continue; } - if (property.NameEquals("echo"u8)) + if (prop.NameEquals("echo"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { echo = null; continue; } - echo = property.Value.GetBoolean(); + echo = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("frequency_penalty"u8)) + if (prop.NameEquals("frequency_penalty"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { frequencyPenalty = null; continue; } - frequencyPenalty = property.Value.GetSingle(); + frequencyPenalty = prop.Value.GetSingle(); continue; } - if (property.NameEquals("logit_bias"u8)) + if (prop.NameEquals("logit_bias"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetInt32()); + dictionary.Add(prop0.Name, prop0.Value.GetInt32()); } logitBias = dictionary; continue; } - if (property.NameEquals("logprobs"u8)) + if (prop.NameEquals("logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { logprobs = null; continue; } - logprobs = property.Value.GetInt32(); + logprobs = prop.Value.GetInt32(); continue; } - if (property.NameEquals("max_tokens"u8)) + if (prop.NameEquals("max_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { maxTokens = null; continue; } - maxTokens = property.Value.GetInt32(); + maxTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("n"u8)) + if (prop.NameEquals("n"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { n = null; continue; } - n = property.Value.GetInt32(); + n = prop.Value.GetInt32(); continue; } - if (property.NameEquals("presence_penalty"u8)) + if (prop.NameEquals("presence_penalty"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { presencePenalty = null; continue; } - presencePenalty = property.Value.GetSingle(); + presencePenalty = prop.Value.GetSingle(); continue; } - if (property.NameEquals("seed"u8)) + if (prop.NameEquals("seed"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { seed = null; continue; } - seed = property.Value.GetInt64(); + seed = prop.Value.GetInt64(); continue; } - if (property.NameEquals("stop"u8)) + if (prop.NameEquals("stop"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { stop = null; continue; } - stop = BinaryData.FromString(property.Value.GetRawText()); + stop = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("stream"u8)) + if (prop.NameEquals("stream"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { stream = null; continue; } - stream = property.Value.GetBoolean(); + stream = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("stream_options"u8)) + if (prop.NameEquals("stream_options"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { streamOptions = null; continue; } - streamOptions = InternalChatCompletionStreamOptions.DeserializeInternalChatCompletionStreamOptions(property.Value, options); + streamOptions = InternalChatCompletionStreamOptions.DeserializeInternalChatCompletionStreamOptions(prop.Value, options); continue; } - if (property.NameEquals("suffix"u8)) + if (prop.NameEquals("suffix"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { suffix = null; continue; } - suffix = property.Value.GetString(); + suffix = prop.Value.GetString(); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { temperature = null; continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { topP = null; continue; } - topP = property.Value.GetSingle(); + topP = prop.Value.GetSingle(); continue; } - if (property.NameEquals("user"u8)) + if (prop.NameEquals("user"u8)) { - user = property.Value.GetString(); + user = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalCreateCompletionRequest( model, prompt, @@ -508,13 +513,14 @@ internal static InternalCreateCompletionRequest DeserializeInternalCreateComplet temperature, topP, user, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -524,15 +530,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalCreateCompletionRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateCompletionRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateCompletionRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateCompletionRequest(document.RootElement, options); } default: @@ -542,15 +549,20 @@ InternalCreateCompletionRequest IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateCompletionRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateCompletionRequest internalCreateCompletionRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateCompletionRequest(document.RootElement); + if (internalCreateCompletionRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateCompletionRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateCompletionRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateCompletionRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateCompletionRequest.cs b/src/Generated/Models/InternalCreateCompletionRequest.cs index 25e584d3b..ed74588e9 100644 --- a/src/Generated/Models/InternalCreateCompletionRequest.cs +++ b/src/Generated/Models/InternalCreateCompletionRequest.cs @@ -4,13 +4,15 @@ using System; using System.Collections.Generic; +using OpenAI; using OpenAI.Chat; namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateCompletionRequest(InternalCreateCompletionRequestModel model, BinaryData prompt) { Model = model; @@ -18,7 +20,7 @@ public InternalCreateCompletionRequest(InternalCreateCompletionRequestModel mode LogitBias = new ChangeTrackingDictionary(); } - internal InternalCreateCompletionRequest(InternalCreateCompletionRequestModel model, BinaryData prompt, int? bestOf, bool? echo, float? frequencyPenalty, IDictionary logitBias, int? logprobs, int? maxTokens, int? n, float? presencePenalty, long? seed, BinaryData stop, bool? stream, InternalChatCompletionStreamOptions streamOptions, string suffix, float? temperature, float? topP, string user, IDictionary serializedAdditionalRawData) + internal InternalCreateCompletionRequest(InternalCreateCompletionRequestModel model, BinaryData prompt, int? bestOf, bool? echo, float? frequencyPenalty, IDictionary logitBias, int? logprobs, int? maxTokens, int? n, float? presencePenalty, long? seed, BinaryData stop, bool? stream, InternalChatCompletionStreamOptions streamOptions, string suffix, float? temperature, float? topP, string user, IDictionary additionalBinaryDataProperties) { Model = model; Prompt = prompt; @@ -38,30 +40,49 @@ internal InternalCreateCompletionRequest(InternalCreateCompletionRequestModel mo Temperature = temperature; TopP = topP; User = user; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateCompletionRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateCompletionRequestModel Model { get; } + public BinaryData Prompt { get; } + public int? BestOf { get; set; } + public bool? Echo { get; set; } + public float? FrequencyPenalty { get; set; } + public IDictionary LogitBias { get; set; } + public int? Logprobs { get; set; } + public int? MaxTokens { get; set; } + public int? N { get; set; } + public float? PresencePenalty { get; set; } + public long? Seed { get; set; } + public BinaryData Stop { get; set; } + public bool? Stream { get; set; } + public InternalChatCompletionStreamOptions StreamOptions { get; set; } + public string Suffix { get; set; } + public float? Temperature { get; set; } + public float? TopP { get; set; } + public string User { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateCompletionRequestModel.cs b/src/Generated/Models/InternalCreateCompletionRequestModel.cs index 46b5e9d0f..3e195b568 100644 --- a/src/Generated/Models/InternalCreateCompletionRequestModel.cs +++ b/src/Generated/Models/InternalCreateCompletionRequestModel.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.LegacyCompletions { internal readonly partial struct InternalCreateCompletionRequestModel : IEquatable { private readonly string _value; + private const string Gpt35TurboInstructValue = "gpt-3.5-turbo-instruct"; + private const string Davinci002Value = "davinci-002"; + private const string Babbage002Value = "babbage-002"; public InternalCreateCompletionRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Gpt35TurboInstructValue = "gpt-3.5-turbo-instruct"; - private const string Davinci002Value = "davinci-002"; - private const string Babbage002Value = "babbage-002"; + _value = value; + } public static InternalCreateCompletionRequestModel Gpt35TurboInstruct { get; } = new InternalCreateCompletionRequestModel(Gpt35TurboInstructValue); + public static InternalCreateCompletionRequestModel Davinci002 { get; } = new InternalCreateCompletionRequestModel(Davinci002Value); + public static InternalCreateCompletionRequestModel Babbage002 { get; } = new InternalCreateCompletionRequestModel(Babbage002Value); + public static bool operator ==(InternalCreateCompletionRequestModel left, InternalCreateCompletionRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateCompletionRequestModel left, InternalCreateCompletionRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateCompletionRequestModel(string value) => new InternalCreateCompletionRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateCompletionRequestModel other && Equals(other); + public bool Equals(InternalCreateCompletionRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateCompletionResponse.Serialization.cs b/src/Generated/Models/InternalCreateCompletionResponse.Serialization.cs index 7f641dc9b..8ff5921f9 100644 --- a/src/Generated/Models/InternalCreateCompletionResponse.Serialization.cs +++ b/src/Generated/Models/InternalCreateCompletionResponse.Serialization.cs @@ -7,64 +7,74 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Chat; namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionResponse : IJsonModel { + internal InternalCreateCompletionResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateCompletionResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("choices") != true) + if (_additionalBinaryDataProperties?.ContainsKey("choices") != true) { writer.WritePropertyName("choices"u8); writer.WriteStartArray(); - foreach (var item in Choices) + foreach (InternalCreateCompletionResponseChoice item in Choices) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("created") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) { writer.WritePropertyName("created"u8); writer.WriteNumberValue(Created, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) + if (Optional.IsDefined(SystemFingerprint) && _additionalBinaryDataProperties?.ContainsKey("system_fingerprint") != true) { writer.WritePropertyName("system_fingerprint"u8); writer.WriteStringValue(SystemFingerprint); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true && Optional.IsDefined(Usage)) + if (Optional.IsDefined(Usage) && _additionalBinaryDataProperties?.ContainsKey("usage") != true) { writer.WritePropertyName("usage"u8); writer.WriteObjectValue(Usage, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -72,7 +82,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -81,91 +91,86 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalCreateCompletionResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateCompletionResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateCompletionResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateCompletionResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateCompletionResponse(document.RootElement, options); } - internal static InternalCreateCompletionResponse DeserializeInternalCreateCompletionResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateCompletionResponse DeserializeInternalCreateCompletionResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - IReadOnlyList choices = default; + IList choices = default; DateTimeOffset created = default; string model = default; string systemFingerprint = default; InternalCreateCompletionResponseObject @object = default; ChatTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("choices"u8)) + if (prop.NameEquals("choices"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalCreateCompletionResponseChoice.DeserializeInternalCreateCompletionResponseChoice(item, options)); } choices = array; continue; } - if (property.NameEquals("created"u8)) + if (prop.NameEquals("created"u8)) { - created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + created = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("system_fingerprint"u8)) + if (prop.NameEquals("system_fingerprint"u8)) { - systemFingerprint = property.Value.GetString(); + systemFingerprint = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalCreateCompletionResponseObject(property.Value.GetString()); + @object = new InternalCreateCompletionResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - usage = ChatTokenUsage.DeserializeChatTokenUsage(property.Value, options); + usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalCreateCompletionResponse( id, choices, @@ -174,13 +179,14 @@ internal static InternalCreateCompletionResponse DeserializeInternalCreateComple systemFingerprint, @object, usage, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -190,15 +196,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalCreateCompletionResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateCompletionResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateCompletionResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateCompletionResponse(document.RootElement, options); } default: @@ -208,15 +215,20 @@ InternalCreateCompletionResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateCompletionResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateCompletionResponse internalCreateCompletionResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateCompletionResponse(document.RootElement); + if (internalCreateCompletionResponse == null) + { + return null; + } + return BinaryContent.Create(internalCreateCompletionResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateCompletionResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateCompletionResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponse.cs b/src/Generated/Models/InternalCreateCompletionResponse.cs index b7dd5c2a4..c77eb92c6 100644 --- a/src/Generated/Models/InternalCreateCompletionResponse.cs +++ b/src/Generated/Models/InternalCreateCompletionResponse.cs @@ -11,20 +11,17 @@ namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateCompletionResponse(string id, IEnumerable choices, DateTimeOffset created, string model) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(choices, nameof(choices)); - Argument.AssertNotNull(model, nameof(model)); - Id = id; Choices = choices.ToList(); Created = created; Model = model; } - internal InternalCreateCompletionResponse(string id, IReadOnlyList choices, DateTimeOffset created, string model, string systemFingerprint, InternalCreateCompletionResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal InternalCreateCompletionResponse(string id, IList choices, DateTimeOffset created, string model, string systemFingerprint, InternalCreateCompletionResponseObject @object, ChatTokenUsage usage, IDictionary additionalBinaryDataProperties) { Id = id; Choices = choices; @@ -33,20 +30,27 @@ internal InternalCreateCompletionResponse(string id, IReadOnlyList Choices { get; } + + public IList Choices { get; } + public DateTimeOffset Created { get; } + public string Model { get; } + public string SystemFingerprint { get; } - public InternalCreateCompletionResponseObject Object { get; } = InternalCreateCompletionResponseObject.TextCompletion; + + public InternalCreateCompletionResponseObject Object { get; } = "text_completion"; public ChatTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseChoice.Serialization.cs b/src/Generated/Models/InternalCreateCompletionResponseChoice.Serialization.cs index b49151000..1979a5fe2 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseChoice.Serialization.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseChoice.Serialization.cs @@ -7,31 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionResponseChoice : IJsonModel { + internal InternalCreateCompletionResponseChoice() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateCompletionResponseChoice)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("finish_reason") != true) + if (_additionalBinaryDataProperties?.ContainsKey("finish_reason") != true) { writer.WritePropertyName("finish_reason"u8); writer.WriteStringValue(FinishReason.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("logprobs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("logprobs") != true) { if (Logprobs != null) { @@ -40,17 +50,17 @@ void IJsonModel.Write(Utf8JsonWriter wri } else { - writer.WriteNull("logprobs"); + writer.WriteNull("logprobs"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -58,7 +68,7 @@ void IJsonModel.Write(Utf8JsonWriter wri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -67,25 +77,23 @@ void IJsonModel.Write(Utf8JsonWriter wri #endif } } - writer.WriteEndObject(); } - InternalCreateCompletionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateCompletionResponseChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateCompletionResponseChoice JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateCompletionResponseChoice)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateCompletionResponseChoice(document.RootElement, options); } - internal static InternalCreateCompletionResponseChoice DeserializeInternalCreateCompletionResponseChoice(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateCompletionResponseChoice DeserializeInternalCreateCompletionResponseChoice(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -94,49 +102,47 @@ internal static InternalCreateCompletionResponseChoice DeserializeInternalCreate int index = default; InternalCreateCompletionResponseChoiceLogprobs logprobs = default; string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("finish_reason"u8)) + if (prop.NameEquals("finish_reason"u8)) { - finishReason = new InternalCreateCompletionResponseChoiceFinishReason(property.Value.GetString()); + finishReason = new InternalCreateCompletionResponseChoiceFinishReason(prop.Value.GetString()); continue; } - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("logprobs"u8)) + if (prop.NameEquals("logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { logprobs = null; continue; } - logprobs = InternalCreateCompletionResponseChoiceLogprobs.DeserializeInternalCreateCompletionResponseChoiceLogprobs(property.Value, options); + logprobs = InternalCreateCompletionResponseChoiceLogprobs.DeserializeInternalCreateCompletionResponseChoiceLogprobs(prop.Value, options); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateCompletionResponseChoice(finishReason, index, logprobs, text, serializedAdditionalRawData); + return new InternalCreateCompletionResponseChoice(finishReason, index, logprobs, text, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -146,15 +152,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalCreateCompletionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateCompletionResponseChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateCompletionResponseChoice 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateCompletionResponseChoice(document.RootElement, options); } default: @@ -164,15 +171,20 @@ InternalCreateCompletionResponseChoice IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateCompletionResponseChoice FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateCompletionResponseChoice internalCreateCompletionResponseChoice) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateCompletionResponseChoice(document.RootElement); + if (internalCreateCompletionResponseChoice == null) + { + return null; + } + return BinaryContent.Create(internalCreateCompletionResponseChoice, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateCompletionResponseChoice(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateCompletionResponseChoice(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseChoice.cs b/src/Generated/Models/InternalCreateCompletionResponseChoice.cs index 5aa7f0cca..e9391f1b8 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseChoice.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseChoice.cs @@ -9,33 +9,37 @@ namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionResponseChoice { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateCompletionResponseChoice(InternalCreateCompletionResponseChoiceFinishReason finishReason, int index, InternalCreateCompletionResponseChoiceLogprobs logprobs, string text) { - Argument.AssertNotNull(text, nameof(text)); - FinishReason = finishReason; Index = index; Logprobs = logprobs; Text = text; } - internal InternalCreateCompletionResponseChoice(InternalCreateCompletionResponseChoiceFinishReason finishReason, int index, InternalCreateCompletionResponseChoiceLogprobs logprobs, string text, IDictionary serializedAdditionalRawData) + internal InternalCreateCompletionResponseChoice(InternalCreateCompletionResponseChoiceFinishReason finishReason, int index, InternalCreateCompletionResponseChoiceLogprobs logprobs, string text, IDictionary additionalBinaryDataProperties) { FinishReason = finishReason; Index = index; Logprobs = logprobs; Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateCompletionResponseChoice() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateCompletionResponseChoiceFinishReason FinishReason { get; } + public int Index { get; } + public InternalCreateCompletionResponseChoiceLogprobs Logprobs { get; } + public string Text { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseChoiceFinishReason.cs b/src/Generated/Models/InternalCreateCompletionResponseChoiceFinishReason.cs index e10b1ef37..9754837fc 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseChoiceFinishReason.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseChoiceFinishReason.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.LegacyCompletions { internal readonly partial struct InternalCreateCompletionResponseChoiceFinishReason : IEquatable { private readonly string _value; + private const string StopValue = "stop"; + private const string LengthValue = "length"; + private const string ContentFilterValue = "content_filter"; public InternalCreateCompletionResponseChoiceFinishReason(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string StopValue = "stop"; - private const string LengthValue = "length"; - private const string ContentFilterValue = "content_filter"; + _value = value; + } public static InternalCreateCompletionResponseChoiceFinishReason Stop { get; } = new InternalCreateCompletionResponseChoiceFinishReason(StopValue); + public static InternalCreateCompletionResponseChoiceFinishReason Length { get; } = new InternalCreateCompletionResponseChoiceFinishReason(LengthValue); + public static InternalCreateCompletionResponseChoiceFinishReason ContentFilter { get; } = new InternalCreateCompletionResponseChoiceFinishReason(ContentFilterValue); + public static bool operator ==(InternalCreateCompletionResponseChoiceFinishReason left, InternalCreateCompletionResponseChoiceFinishReason right) => left.Equals(right); + public static bool operator !=(InternalCreateCompletionResponseChoiceFinishReason left, InternalCreateCompletionResponseChoiceFinishReason right) => !left.Equals(right); + public static implicit operator InternalCreateCompletionResponseChoiceFinishReason(string value) => new InternalCreateCompletionResponseChoiceFinishReason(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateCompletionResponseChoiceFinishReason other && Equals(other); + public bool Equals(InternalCreateCompletionResponseChoiceFinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.Serialization.cs b/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.Serialization.cs index 9117d8366..c47f11632 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.Serialization.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.LegacyCompletions { @@ -14,48 +15,58 @@ internal partial class InternalCreateCompletionResponseChoiceLogprobs : IJsonMod { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateCompletionResponseChoiceLogprobs)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text_offset") != true && Optional.IsCollectionDefined(TextOffset)) + if (Optional.IsCollectionDefined(TextOffset) && _additionalBinaryDataProperties?.ContainsKey("text_offset") != true) { writer.WritePropertyName("text_offset"u8); writer.WriteStartArray(); - foreach (var item in TextOffset) + foreach (int item in TextOffset) { writer.WriteNumberValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("token_logprobs") != true && Optional.IsCollectionDefined(TokenLogprobs)) + if (Optional.IsCollectionDefined(TokenLogprobs) && _additionalBinaryDataProperties?.ContainsKey("token_logprobs") != true) { writer.WritePropertyName("token_logprobs"u8); writer.WriteStartArray(); - foreach (var item in TokenLogprobs) + foreach (float item in TokenLogprobs) { writer.WriteNumberValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tokens") != true && Optional.IsCollectionDefined(Tokens)) + if (Optional.IsCollectionDefined(Tokens) && _additionalBinaryDataProperties?.ContainsKey("tokens") != true) { writer.WritePropertyName("tokens"u8); writer.WriteStartArray(); - foreach (var item in Tokens) + foreach (string item in Tokens) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("top_logprobs") != true && Optional.IsCollectionDefined(TopLogprobs)) + if (Optional.IsCollectionDefined(TopLogprobs) && _additionalBinaryDataProperties?.ContainsKey("top_logprobs") != true) { writer.WritePropertyName("top_logprobs"u8); writer.WriteStartArray(); - foreach (var item in TopLogprobs) + foreach (IDictionary item in TopLogprobs) { if (item == null) { @@ -72,9 +83,9 @@ void IJsonModel.Write(Utf8JsonWr } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -82,7 +93,7 @@ void IJsonModel.Write(Utf8JsonWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -91,87 +102,91 @@ void IJsonModel.Write(Utf8JsonWr #endif } } - writer.WriteEndObject(); } - InternalCreateCompletionResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateCompletionResponseChoiceLogprobs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateCompletionResponseChoiceLogprobs JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateCompletionResponseChoiceLogprobs)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateCompletionResponseChoiceLogprobs(document.RootElement, options); } - internal static InternalCreateCompletionResponseChoiceLogprobs DeserializeInternalCreateCompletionResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateCompletionResponseChoiceLogprobs DeserializeInternalCreateCompletionResponseChoiceLogprobs(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList textOffset = default; - IReadOnlyList tokenLogprobs = default; - IReadOnlyList tokens = default; - IReadOnlyList> topLogprobs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList textOffset = default; + IList tokenLogprobs = default; + IList tokens = default; + IList> topLogprobs = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text_offset"u8)) + if (prop.NameEquals("text_offset"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(item.GetInt32()); } textOffset = array; continue; } - if (property.NameEquals("token_logprobs"u8)) + if (prop.NameEquals("token_logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(item.GetSingle()); } tokenLogprobs = array; continue; } - if (property.NameEquals("tokens"u8)) + if (prop.NameEquals("tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } tokens = array; continue; } - if (property.NameEquals("top_logprobs"u8)) + if (prop.NameEquals("top_logprobs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List> array = new List>(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { @@ -180,9 +195,9 @@ internal static InternalCreateCompletionResponseChoiceLogprobs DeserializeIntern else { Dictionary dictionary = new Dictionary(); - foreach (var property0 in item.EnumerateObject()) + foreach (var prop0 in item.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetSingle()); + dictionary.Add(prop0.Name, prop0.Value.GetSingle()); } array.Add(dictionary); } @@ -192,18 +207,17 @@ internal static InternalCreateCompletionResponseChoiceLogprobs DeserializeIntern } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateCompletionResponseChoiceLogprobs(textOffset ?? new ChangeTrackingList(), tokenLogprobs ?? new ChangeTrackingList(), tokens ?? new ChangeTrackingList(), topLogprobs ?? new ChangeTrackingList>(), serializedAdditionalRawData); + return new InternalCreateCompletionResponseChoiceLogprobs(textOffset ?? new ChangeTrackingList(), tokenLogprobs ?? new ChangeTrackingList(), tokens ?? new ChangeTrackingList(), topLogprobs ?? new ChangeTrackingList>(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -213,15 +227,16 @@ BinaryData IPersistableModel.Wri } } - InternalCreateCompletionResponseChoiceLogprobs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateCompletionResponseChoiceLogprobs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateCompletionResponseChoiceLogprobs 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateCompletionResponseChoiceLogprobs(document.RootElement, options); } default: @@ -231,15 +246,20 @@ InternalCreateCompletionResponseChoiceLogprobs IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateCompletionResponseChoiceLogprobs FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateCompletionResponseChoiceLogprobs internalCreateCompletionResponseChoiceLogprobs) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateCompletionResponseChoiceLogprobs(document.RootElement); + if (internalCreateCompletionResponseChoiceLogprobs == null) + { + return null; + } + return BinaryContent.Create(internalCreateCompletionResponseChoiceLogprobs, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateCompletionResponseChoiceLogprobs(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateCompletionResponseChoiceLogprobs(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.cs b/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.cs index 6f5de82a3..a19f2969e 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseChoiceLogprobs.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.LegacyCompletions { internal partial class InternalCreateCompletionResponseChoiceLogprobs { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateCompletionResponseChoiceLogprobs() { TextOffset = new ChangeTrackingList(); @@ -18,18 +20,27 @@ internal InternalCreateCompletionResponseChoiceLogprobs() TopLogprobs = new ChangeTrackingList>(); } - internal InternalCreateCompletionResponseChoiceLogprobs(IReadOnlyList textOffset, IReadOnlyList tokenLogprobs, IReadOnlyList tokens, IReadOnlyList> topLogprobs, IDictionary serializedAdditionalRawData) + internal InternalCreateCompletionResponseChoiceLogprobs(IList textOffset, IList tokenLogprobs, IList tokens, IList> topLogprobs, IDictionary additionalBinaryDataProperties) { TextOffset = textOffset; TokenLogprobs = tokenLogprobs; Tokens = tokens; TopLogprobs = topLogprobs; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public IReadOnlyList TextOffset { get; } - public IReadOnlyList TokenLogprobs { get; } - public IReadOnlyList Tokens { get; } - public IReadOnlyList> TopLogprobs { get; } + public IList TextOffset { get; } + + public IList TokenLogprobs { get; } + + public IList Tokens { get; } + + public IList> TopLogprobs { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateCompletionResponseObject.cs b/src/Generated/Models/InternalCreateCompletionResponseObject.cs index 8dfbd3475..1ef3b7e97 100644 --- a/src/Generated/Models/InternalCreateCompletionResponseObject.cs +++ b/src/Generated/Models/InternalCreateCompletionResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.LegacyCompletions { internal readonly partial struct InternalCreateCompletionResponseObject : IEquatable { private readonly string _value; + private const string TextCompletionValue = "text_completion"; public InternalCreateCompletionResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextCompletionValue = "text_completion"; + _value = value; + } public static InternalCreateCompletionResponseObject TextCompletion { get; } = new InternalCreateCompletionResponseObject(TextCompletionValue); + public static bool operator ==(InternalCreateCompletionResponseObject left, InternalCreateCompletionResponseObject right) => left.Equals(right); + public static bool operator !=(InternalCreateCompletionResponseObject left, InternalCreateCompletionResponseObject right) => !left.Equals(right); + public static implicit operator InternalCreateCompletionResponseObject(string value) => new InternalCreateCompletionResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateCompletionResponseObject other && Equals(other); + public bool Equals(InternalCreateCompletionResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateEmbeddingRequestEncodingFormat.cs b/src/Generated/Models/InternalCreateEmbeddingRequestEncodingFormat.cs index 6f59eb8e5..d868925d3 100644 --- a/src/Generated/Models/InternalCreateEmbeddingRequestEncodingFormat.cs +++ b/src/Generated/Models/InternalCreateEmbeddingRequestEncodingFormat.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Embeddings { internal readonly partial struct InternalCreateEmbeddingRequestEncodingFormat : IEquatable { private readonly string _value; + private const string FloatValue = "float"; + private const string Base64Value = "base64"; public InternalCreateEmbeddingRequestEncodingFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FloatValue = "float"; - private const string Base64Value = "base64"; + _value = value; + } public static InternalCreateEmbeddingRequestEncodingFormat Float { get; } = new InternalCreateEmbeddingRequestEncodingFormat(FloatValue); + public static InternalCreateEmbeddingRequestEncodingFormat Base64 { get; } = new InternalCreateEmbeddingRequestEncodingFormat(Base64Value); + public static bool operator ==(InternalCreateEmbeddingRequestEncodingFormat left, InternalCreateEmbeddingRequestEncodingFormat right) => left.Equals(right); + public static bool operator !=(InternalCreateEmbeddingRequestEncodingFormat left, InternalCreateEmbeddingRequestEncodingFormat right) => !left.Equals(right); + public static implicit operator InternalCreateEmbeddingRequestEncodingFormat(string value) => new InternalCreateEmbeddingRequestEncodingFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateEmbeddingRequestEncodingFormat other && Equals(other); + public bool Equals(InternalCreateEmbeddingRequestEncodingFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateEmbeddingRequestModel.cs b/src/Generated/Models/InternalCreateEmbeddingRequestModel.cs index 98fa114a0..c2467f535 100644 --- a/src/Generated/Models/InternalCreateEmbeddingRequestModel.cs +++ b/src/Generated/Models/InternalCreateEmbeddingRequestModel.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Embeddings { internal readonly partial struct InternalCreateEmbeddingRequestModel : IEquatable { private readonly string _value; + private const string TextEmbeddingAda002Value = "text-embedding-ada-002"; + private const string TextEmbedding3SmallValue = "text-embedding-3-small"; + private const string TextEmbedding3LargeValue = "text-embedding-3-large"; public InternalCreateEmbeddingRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextEmbeddingAda002Value = "text-embedding-ada-002"; - private const string TextEmbedding3SmallValue = "text-embedding-3-small"; - private const string TextEmbedding3LargeValue = "text-embedding-3-large"; + _value = value; + } public static InternalCreateEmbeddingRequestModel TextEmbeddingAda002 { get; } = new InternalCreateEmbeddingRequestModel(TextEmbeddingAda002Value); + public static InternalCreateEmbeddingRequestModel TextEmbedding3Small { get; } = new InternalCreateEmbeddingRequestModel(TextEmbedding3SmallValue); + public static InternalCreateEmbeddingRequestModel TextEmbedding3Large { get; } = new InternalCreateEmbeddingRequestModel(TextEmbedding3LargeValue); + public static bool operator ==(InternalCreateEmbeddingRequestModel left, InternalCreateEmbeddingRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateEmbeddingRequestModel left, InternalCreateEmbeddingRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateEmbeddingRequestModel(string value) => new InternalCreateEmbeddingRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateEmbeddingRequestModel other && Equals(other); + public bool Equals(InternalCreateEmbeddingRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateEmbeddingResponseObject.cs b/src/Generated/Models/InternalCreateEmbeddingResponseObject.cs index dc8b38632..1f831782a 100644 --- a/src/Generated/Models/InternalCreateEmbeddingResponseObject.cs +++ b/src/Generated/Models/InternalCreateEmbeddingResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Embeddings { internal readonly partial struct InternalCreateEmbeddingResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalCreateEmbeddingResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalCreateEmbeddingResponseObject List { get; } = new InternalCreateEmbeddingResponseObject(ListValue); + public static bool operator ==(InternalCreateEmbeddingResponseObject left, InternalCreateEmbeddingResponseObject right) => left.Equals(right); + public static bool operator !=(InternalCreateEmbeddingResponseObject left, InternalCreateEmbeddingResponseObject right) => !left.Equals(right); + public static implicit operator InternalCreateEmbeddingResponseObject(string value) => new InternalCreateEmbeddingResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateEmbeddingResponseObject other && Equals(other); + public bool Equals(InternalCreateEmbeddingResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs b/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs index e85d5c334..308784743 100644 --- a/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs +++ b/src/Generated/Models/InternalCreateFineTuningJobRequestModel.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalCreateFineTuningJobRequestModel : IEquatable { private readonly string _value; - - public InternalCreateFineTuningJobRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string Babbage002Value = "babbage-002"; private const string Davinci002Value = "davinci-002"; private const string Gpt35TurboValue = "gpt-3.5-turbo"; private const string Gpt4oMiniValue = "gpt-4o-mini"; + public InternalCreateFineTuningJobRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateFineTuningJobRequestModel Babbage002 { get; } = new InternalCreateFineTuningJobRequestModel(Babbage002Value); + public static InternalCreateFineTuningJobRequestModel Davinci002 { get; } = new InternalCreateFineTuningJobRequestModel(Davinci002Value); + public static InternalCreateFineTuningJobRequestModel Gpt35Turbo { get; } = new InternalCreateFineTuningJobRequestModel(Gpt35TurboValue); + public static InternalCreateFineTuningJobRequestModel Gpt4oMini { get; } = new InternalCreateFineTuningJobRequestModel(Gpt4oMiniValue); + public static bool operator ==(InternalCreateFineTuningJobRequestModel left, InternalCreateFineTuningJobRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateFineTuningJobRequestModel left, InternalCreateFineTuningJobRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateFineTuningJobRequestModel(string value) => new InternalCreateFineTuningJobRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateFineTuningJobRequestModel other && Equals(other); + public bool Equals(InternalCreateFineTuningJobRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.Serialization.cs b/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.Serialization.cs index b17e11cfb..ebea86565 100644 --- a/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.Serialization.cs +++ b/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.Serialization.cs @@ -7,26 +7,31 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalCreateFineTuningJobRequestWandbIntegrationWandb : IJsonModel { + internal InternalCreateFineTuningJobRequestWandbIntegrationWandb() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateFineTuningJobRequestWandbIntegrationWandb)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("project") != true) - { - writer.WritePropertyName("project"u8); - writer.WriteStringValue(Project); - } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -35,10 +40,10 @@ void IJsonModel.Write(U } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("entity") != true && Optional.IsDefined(Entity)) + if (Optional.IsDefined(Entity) && _additionalBinaryDataProperties?.ContainsKey("entity") != true) { if (Entity != null) { @@ -47,22 +52,32 @@ void IJsonModel.Write(U } else { - writer.WriteNull("entity"); + writer.WriteNull("entity"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tags") != true && Optional.IsCollectionDefined(Tags)) + if (Optional.IsCollectionDefined(Tags) && _additionalBinaryDataProperties?.ContainsKey("tags") != true) { writer.WritePropertyName("tags"u8); writer.WriteStartArray(); - foreach (var item in Tags) + foreach (string item in Tags) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("project") != true) + { + writer.WritePropertyName("project"u8); + writer.WriteStringValue(Project); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -70,7 +85,7 @@ void IJsonModel.Write(U } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -79,90 +94,93 @@ void IJsonModel.Write(U #endif } } - writer.WriteEndObject(); } - InternalCreateFineTuningJobRequestWandbIntegrationWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateFineTuningJobRequestWandbIntegrationWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateFineTuningJobRequestWandbIntegrationWandb JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateFineTuningJobRequestWandbIntegrationWandb)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(document.RootElement, options); } - internal static InternalCreateFineTuningJobRequestWandbIntegrationWandb DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateFineTuningJobRequestWandbIntegrationWandb DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string project = default; string name = default; string entity = default; IList tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string project = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("project"u8)) - { - project = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("entity"u8)) + if (prop.NameEquals("entity"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { entity = null; continue; } - entity = property.Value.GetString(); + entity = prop.Value.GetString(); continue; } - if (property.NameEquals("tags"u8)) + if (prop.NameEquals("tags"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } tags = array; continue; } + if (prop.NameEquals("project"u8)) + { + project = prop.Value.GetString(); + continue; + } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateFineTuningJobRequestWandbIntegrationWandb(project, name, entity, tags ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalCreateFineTuningJobRequestWandbIntegrationWandb(name, entity, tags ?? new ChangeTrackingList(), project, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -172,15 +190,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateFineTuningJobRequestWandbIntegrationWandb IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateFineTuningJobRequestWandbIntegrationWandb 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(document.RootElement, options); } default: @@ -190,15 +209,20 @@ InternalCreateFineTuningJobRequestWandbIntegrationWandb IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateFineTuningJobRequestWandbIntegrationWandb FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateFineTuningJobRequestWandbIntegrationWandb internalCreateFineTuningJobRequestWandbIntegrationWandb) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(document.RootElement); + if (internalCreateFineTuningJobRequestWandbIntegrationWandb == null) + { + return null; + } + return BinaryContent.Create(internalCreateFineTuningJobRequestWandbIntegrationWandb, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateFineTuningJobRequestWandbIntegrationWandb(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.cs b/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.cs index bd389026b..7db538e27 100644 --- a/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.cs +++ b/src/Generated/Models/InternalCreateFineTuningJobRequestWandbIntegrationWandb.cs @@ -4,34 +4,41 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalCreateFineTuningJobRequestWandbIntegrationWandb { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateFineTuningJobRequestWandbIntegrationWandb(string project) { Argument.AssertNotNull(project, nameof(project)); - Project = project; Tags = new ChangeTrackingList(); + Project = project; } - internal InternalCreateFineTuningJobRequestWandbIntegrationWandb(string project, string name, string entity, IList tags, IDictionary serializedAdditionalRawData) + internal InternalCreateFineTuningJobRequestWandbIntegrationWandb(string name, string entity, IList tags, string project, IDictionary additionalBinaryDataProperties) { - Project = project; Name = name; Entity = entity; Tags = tags; - SerializedAdditionalRawData = serializedAdditionalRawData; + Project = project; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateFineTuningJobRequestWandbIntegrationWandb() - { - } public string Name { get; set; } + public string Entity { get; set; } + public IList Tags { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateImageEditRequestModel.cs b/src/Generated/Models/InternalCreateImageEditRequestModel.cs index c1ae8ba57..1ba31ad3a 100644 --- a/src/Generated/Models/InternalCreateImageEditRequestModel.cs +++ b/src/Generated/Models/InternalCreateImageEditRequestModel.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageEditRequestModel : IEquatable { private readonly string _value; + private const string DallE2Value = "dall-e-2"; public InternalCreateImageEditRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string DallE2Value = "dall-e-2"; + _value = value; + } public static InternalCreateImageEditRequestModel DallE2 { get; } = new InternalCreateImageEditRequestModel(DallE2Value); + public static bool operator ==(InternalCreateImageEditRequestModel left, InternalCreateImageEditRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateImageEditRequestModel left, InternalCreateImageEditRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateImageEditRequestModel(string value) => new InternalCreateImageEditRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageEditRequestModel other && Equals(other); + public bool Equals(InternalCreateImageEditRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageEditRequestResponseFormat.cs b/src/Generated/Models/InternalCreateImageEditRequestResponseFormat.cs index 7da85fee8..597c1e8a9 100644 --- a/src/Generated/Models/InternalCreateImageEditRequestResponseFormat.cs +++ b/src/Generated/Models/InternalCreateImageEditRequestResponseFormat.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageEditRequestResponseFormat : IEquatable { private readonly string _value; + private const string UrlValue = "url"; + private const string B64JsonValue = "b64_json"; public InternalCreateImageEditRequestResponseFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UrlValue = "url"; - private const string B64JsonValue = "b64_json"; + _value = value; + } public static InternalCreateImageEditRequestResponseFormat Url { get; } = new InternalCreateImageEditRequestResponseFormat(UrlValue); + public static InternalCreateImageEditRequestResponseFormat B64Json { get; } = new InternalCreateImageEditRequestResponseFormat(B64JsonValue); + public static bool operator ==(InternalCreateImageEditRequestResponseFormat left, InternalCreateImageEditRequestResponseFormat right) => left.Equals(right); + public static bool operator !=(InternalCreateImageEditRequestResponseFormat left, InternalCreateImageEditRequestResponseFormat right) => !left.Equals(right); + public static implicit operator InternalCreateImageEditRequestResponseFormat(string value) => new InternalCreateImageEditRequestResponseFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageEditRequestResponseFormat other && Equals(other); + public bool Equals(InternalCreateImageEditRequestResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageEditRequestSize.cs b/src/Generated/Models/InternalCreateImageEditRequestSize.cs index 122d3fc3b..abedecc3a 100644 --- a/src/Generated/Models/InternalCreateImageEditRequestSize.cs +++ b/src/Generated/Models/InternalCreateImageEditRequestSize.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageEditRequestSize : IEquatable { private readonly string _value; + private const string _256x256Value = "256x256"; + private const string _512x512Value = "512x512"; + private const string _1024x1024Value = "1024x1024"; public InternalCreateImageEditRequestSize(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string _256x256Value = "256x256"; - private const string _512x512Value = "512x512"; - private const string _1024x1024Value = "1024x1024"; + _value = value; + } public static InternalCreateImageEditRequestSize _256x256 { get; } = new InternalCreateImageEditRequestSize(_256x256Value); + public static InternalCreateImageEditRequestSize _512x512 { get; } = new InternalCreateImageEditRequestSize(_512x512Value); + public static InternalCreateImageEditRequestSize _1024x1024 { get; } = new InternalCreateImageEditRequestSize(_1024x1024Value); + public static bool operator ==(InternalCreateImageEditRequestSize left, InternalCreateImageEditRequestSize right) => left.Equals(right); + public static bool operator !=(InternalCreateImageEditRequestSize left, InternalCreateImageEditRequestSize right) => !left.Equals(right); + public static implicit operator InternalCreateImageEditRequestSize(string value) => new InternalCreateImageEditRequestSize(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageEditRequestSize other && Equals(other); + public bool Equals(InternalCreateImageEditRequestSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageRequestModel.cs b/src/Generated/Models/InternalCreateImageRequestModel.cs index a43ec9fc4..d5d2c8e89 100644 --- a/src/Generated/Models/InternalCreateImageRequestModel.cs +++ b/src/Generated/Models/InternalCreateImageRequestModel.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageRequestModel : IEquatable { private readonly string _value; + private const string DallE2Value = "dall-e-2"; + private const string DallE3Value = "dall-e-3"; public InternalCreateImageRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string DallE2Value = "dall-e-2"; - private const string DallE3Value = "dall-e-3"; + _value = value; + } public static InternalCreateImageRequestModel DallE2 { get; } = new InternalCreateImageRequestModel(DallE2Value); + public static InternalCreateImageRequestModel DallE3 { get; } = new InternalCreateImageRequestModel(DallE3Value); + public static bool operator ==(InternalCreateImageRequestModel left, InternalCreateImageRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateImageRequestModel left, InternalCreateImageRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateImageRequestModel(string value) => new InternalCreateImageRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageRequestModel other && Equals(other); + public bool Equals(InternalCreateImageRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageVariationRequestModel.cs b/src/Generated/Models/InternalCreateImageVariationRequestModel.cs index 2f57438b8..10a223fed 100644 --- a/src/Generated/Models/InternalCreateImageVariationRequestModel.cs +++ b/src/Generated/Models/InternalCreateImageVariationRequestModel.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageVariationRequestModel : IEquatable { private readonly string _value; + private const string DallE2Value = "dall-e-2"; public InternalCreateImageVariationRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string DallE2Value = "dall-e-2"; + _value = value; + } public static InternalCreateImageVariationRequestModel DallE2 { get; } = new InternalCreateImageVariationRequestModel(DallE2Value); + public static bool operator ==(InternalCreateImageVariationRequestModel left, InternalCreateImageVariationRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateImageVariationRequestModel left, InternalCreateImageVariationRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateImageVariationRequestModel(string value) => new InternalCreateImageVariationRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageVariationRequestModel other && Equals(other); + public bool Equals(InternalCreateImageVariationRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageVariationRequestResponseFormat.cs b/src/Generated/Models/InternalCreateImageVariationRequestResponseFormat.cs index bb1ed33e1..3d5c9d150 100644 --- a/src/Generated/Models/InternalCreateImageVariationRequestResponseFormat.cs +++ b/src/Generated/Models/InternalCreateImageVariationRequestResponseFormat.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageVariationRequestResponseFormat : IEquatable { private readonly string _value; + private const string UrlValue = "url"; + private const string B64JsonValue = "b64_json"; public InternalCreateImageVariationRequestResponseFormat(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UrlValue = "url"; - private const string B64JsonValue = "b64_json"; + _value = value; + } public static InternalCreateImageVariationRequestResponseFormat Url { get; } = new InternalCreateImageVariationRequestResponseFormat(UrlValue); + public static InternalCreateImageVariationRequestResponseFormat B64Json { get; } = new InternalCreateImageVariationRequestResponseFormat(B64JsonValue); + public static bool operator ==(InternalCreateImageVariationRequestResponseFormat left, InternalCreateImageVariationRequestResponseFormat right) => left.Equals(right); + public static bool operator !=(InternalCreateImageVariationRequestResponseFormat left, InternalCreateImageVariationRequestResponseFormat right) => !left.Equals(right); + public static implicit operator InternalCreateImageVariationRequestResponseFormat(string value) => new InternalCreateImageVariationRequestResponseFormat(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageVariationRequestResponseFormat other && Equals(other); + public bool Equals(InternalCreateImageVariationRequestResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateImageVariationRequestSize.cs b/src/Generated/Models/InternalCreateImageVariationRequestSize.cs index 8a60593b0..a418e0dfa 100644 --- a/src/Generated/Models/InternalCreateImageVariationRequestSize.cs +++ b/src/Generated/Models/InternalCreateImageVariationRequestSize.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Images { internal readonly partial struct InternalCreateImageVariationRequestSize : IEquatable { private readonly string _value; + private const string _256x256Value = "256x256"; + private const string _512x512Value = "512x512"; + private const string _1024x1024Value = "1024x1024"; public InternalCreateImageVariationRequestSize(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string _256x256Value = "256x256"; - private const string _512x512Value = "512x512"; - private const string _1024x1024Value = "1024x1024"; + _value = value; + } public static InternalCreateImageVariationRequestSize _256x256 { get; } = new InternalCreateImageVariationRequestSize(_256x256Value); + public static InternalCreateImageVariationRequestSize _512x512 { get; } = new InternalCreateImageVariationRequestSize(_512x512Value); + public static InternalCreateImageVariationRequestSize _1024x1024 { get; } = new InternalCreateImageVariationRequestSize(_1024x1024Value); + public static bool operator ==(InternalCreateImageVariationRequestSize left, InternalCreateImageVariationRequestSize right) => left.Equals(right); + public static bool operator !=(InternalCreateImageVariationRequestSize left, InternalCreateImageVariationRequestSize right) => !left.Equals(right); + public static implicit operator InternalCreateImageVariationRequestSize(string value) => new InternalCreateImageVariationRequestSize(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateImageVariationRequestSize other && Equals(other); + public bool Equals(InternalCreateImageVariationRequestSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput2.Serialization.cs b/src/Generated/Models/InternalCreateModerationRequestInput2.Serialization.cs index 661bcdc00..7c71777ad 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput2.Serialization.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput2.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInput2 : IJsonModel { + internal InternalCreateModerationRequestInput2() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateModerationRequestInput2)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("image_url") != true) + if (_additionalBinaryDataProperties?.ContainsKey("image_url") != true) { writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(ImageUrl, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalCreateModerationRequestInput2 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateModerationRequestInput2 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateModerationRequestInput2 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateModerationRequestInput2)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateModerationRequestInput2(document.RootElement, options); } - internal static InternalCreateModerationRequestInput2 DeserializeInternalCreateModerationRequestInput2(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateModerationRequestInput2 DeserializeInternalCreateModerationRequestInput2(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalCreateModerationRequestInput2Type type = default; + InternalCreateModerationRequestInput2Type @type = default; InternalCreateModerationRequestInputImageUrl imageUrl = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalCreateModerationRequestInput2Type(property.Value.GetString()); + @type = new InternalCreateModerationRequestInput2Type(prop.Value.GetString()); continue; } - if (property.NameEquals("image_url"u8)) + if (prop.NameEquals("image_url"u8)) { - imageUrl = InternalCreateModerationRequestInputImageUrl.DeserializeInternalCreateModerationRequestInputImageUrl(property.Value, options); + imageUrl = InternalCreateModerationRequestInputImageUrl.DeserializeInternalCreateModerationRequestInputImageUrl(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateModerationRequestInput2(type, imageUrl, serializedAdditionalRawData); + return new InternalCreateModerationRequestInput2(@type, imageUrl, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalCreateModerationRequestInput2 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateModerationRequestInput2 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateModerationRequestInput2 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateModerationRequestInput2(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalCreateModerationRequestInput2 IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateModerationRequestInput2 FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateModerationRequestInput2 internalCreateModerationRequestInput2) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateModerationRequestInput2(document.RootElement); + if (internalCreateModerationRequestInput2 == null) + { + return null; + } + return BinaryContent.Create(internalCreateModerationRequestInput2, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateModerationRequestInput2(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateModerationRequestInput2(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput2.cs b/src/Generated/Models/InternalCreateModerationRequestInput2.cs index 3fe805a1d..8048b07c6 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput2.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput2.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInput2 { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateModerationRequestInput2(InternalCreateModerationRequestInputImageUrl imageUrl) { Argument.AssertNotNull(imageUrl, nameof(imageUrl)); @@ -17,19 +19,21 @@ public InternalCreateModerationRequestInput2(InternalCreateModerationRequestInpu ImageUrl = imageUrl; } - internal InternalCreateModerationRequestInput2(InternalCreateModerationRequestInput2Type type, InternalCreateModerationRequestInputImageUrl imageUrl, IDictionary serializedAdditionalRawData) + internal InternalCreateModerationRequestInput2(InternalCreateModerationRequestInput2Type @type, InternalCreateModerationRequestInputImageUrl imageUrl, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; ImageUrl = imageUrl; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateModerationRequestInput2() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalCreateModerationRequestInput2Type Type { get; } = InternalCreateModerationRequestInput2Type.ImageUrl; + public InternalCreateModerationRequestInput2Type Type { get; } = "image_url"; public InternalCreateModerationRequestInputImageUrl ImageUrl { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput2Type.cs b/src/Generated/Models/InternalCreateModerationRequestInput2Type.cs index eb7ee4bba..72ad5cd40 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput2Type.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput2Type.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Moderations { internal readonly partial struct InternalCreateModerationRequestInput2Type : IEquatable { private readonly string _value; + private const string ImageUrlValue = "image_url"; public InternalCreateModerationRequestInput2Type(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ImageUrlValue = "image_url"; + _value = value; + } public static InternalCreateModerationRequestInput2Type ImageUrl { get; } = new InternalCreateModerationRequestInput2Type(ImageUrlValue); + public static bool operator ==(InternalCreateModerationRequestInput2Type left, InternalCreateModerationRequestInput2Type right) => left.Equals(right); + public static bool operator !=(InternalCreateModerationRequestInput2Type left, InternalCreateModerationRequestInput2Type right) => !left.Equals(right); + public static implicit operator InternalCreateModerationRequestInput2Type(string value) => new InternalCreateModerationRequestInput2Type(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateModerationRequestInput2Type other && Equals(other); + public bool Equals(InternalCreateModerationRequestInput2Type other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput3.Serialization.cs b/src/Generated/Models/InternalCreateModerationRequestInput3.Serialization.cs index a17661a1f..878c6f0be 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput3.Serialization.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput3.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInput3 : IJsonModel { + internal InternalCreateModerationRequestInput3() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateModerationRequestInput3)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalCreateModerationRequestInput3 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateModerationRequestInput3 IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateModerationRequestInput3 JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateModerationRequestInput3)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateModerationRequestInput3(document.RootElement, options); } - internal static InternalCreateModerationRequestInput3 DeserializeInternalCreateModerationRequestInput3(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateModerationRequestInput3 DeserializeInternalCreateModerationRequestInput3(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalCreateModerationRequestInput3Type type = default; + InternalCreateModerationRequestInput3Type @type = default; string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalCreateModerationRequestInput3Type(property.Value.GetString()); + @type = new InternalCreateModerationRequestInput3Type(prop.Value.GetString()); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateModerationRequestInput3(type, text, serializedAdditionalRawData); + return new InternalCreateModerationRequestInput3(@type, text, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalCreateModerationRequestInput3 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateModerationRequestInput3 IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateModerationRequestInput3 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateModerationRequestInput3(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalCreateModerationRequestInput3 IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateModerationRequestInput3 FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateModerationRequestInput3 internalCreateModerationRequestInput3) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateModerationRequestInput3(document.RootElement); + if (internalCreateModerationRequestInput3 == null) + { + return null; + } + return BinaryContent.Create(internalCreateModerationRequestInput3, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateModerationRequestInput3(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateModerationRequestInput3(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput3.cs b/src/Generated/Models/InternalCreateModerationRequestInput3.cs index e5555bc45..7c3522c33 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput3.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput3.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInput3 { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateModerationRequestInput3(string text) { Argument.AssertNotNull(text, nameof(text)); @@ -17,19 +19,21 @@ public InternalCreateModerationRequestInput3(string text) Text = text; } - internal InternalCreateModerationRequestInput3(InternalCreateModerationRequestInput3Type type, string text, IDictionary serializedAdditionalRawData) + internal InternalCreateModerationRequestInput3(InternalCreateModerationRequestInput3Type @type, string text, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateModerationRequestInput3() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalCreateModerationRequestInput3Type Type { get; } = InternalCreateModerationRequestInput3Type.Text; + public InternalCreateModerationRequestInput3Type Type { get; } = "text"; public string Text { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInput3Type.cs b/src/Generated/Models/InternalCreateModerationRequestInput3Type.cs index f0cbeae9d..0e0e22bd9 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInput3Type.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInput3Type.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Moderations { internal readonly partial struct InternalCreateModerationRequestInput3Type : IEquatable { private readonly string _value; + private const string TextValue = "text"; public InternalCreateModerationRequestInput3Type(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextValue = "text"; + _value = value; + } public static InternalCreateModerationRequestInput3Type Text { get; } = new InternalCreateModerationRequestInput3Type(TextValue); + public static bool operator ==(InternalCreateModerationRequestInput3Type left, InternalCreateModerationRequestInput3Type right) => left.Equals(right); + public static bool operator !=(InternalCreateModerationRequestInput3Type left, InternalCreateModerationRequestInput3Type right) => !left.Equals(right); + public static implicit operator InternalCreateModerationRequestInput3Type(string value) => new InternalCreateModerationRequestInput3Type(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateModerationRequestInput3Type other && Equals(other); + public bool Equals(InternalCreateModerationRequestInput3Type other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.Serialization.cs b/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.Serialization.cs index 682022f37..b65ae8776 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.Serialization.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInputImageUrl : IJsonModel { + internal InternalCreateModerationRequestInputImageUrl() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateModerationRequestInputImageUrl)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("url") != true) + if (_additionalBinaryDataProperties?.ContainsKey("url") != true) { writer.WritePropertyName("url"u8); writer.WriteStringValue(Url); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWrit #endif } } - writer.WriteEndObject(); } - InternalCreateModerationRequestInputImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateModerationRequestInputImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateModerationRequestInputImageUrl JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateModerationRequestInputImageUrl)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateModerationRequestInputImageUrl(document.RootElement, options); } - internal static InternalCreateModerationRequestInputImageUrl DeserializeInternalCreateModerationRequestInputImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateModerationRequestInputImageUrl DeserializeInternalCreateModerationRequestInputImageUrl(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string url = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) + if (prop.NameEquals("url"u8)) { - url = property.Value.GetString(); + url = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateModerationRequestInputImageUrl(url, serializedAdditionalRawData); + return new InternalCreateModerationRequestInputImageUrl(url, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write } } - InternalCreateModerationRequestInputImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateModerationRequestInputImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateModerationRequestInputImageUrl 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateModerationRequestInputImageUrl(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalCreateModerationRequestInputImageUrl IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateModerationRequestInputImageUrl FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateModerationRequestInputImageUrl internalCreateModerationRequestInputImageUrl) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateModerationRequestInputImageUrl(document.RootElement); + if (internalCreateModerationRequestInputImageUrl == null) + { + return null; + } + return BinaryContent.Create(internalCreateModerationRequestInputImageUrl, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateModerationRequestInputImageUrl(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateModerationRequestInputImageUrl(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.cs b/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.cs index c611eb77c..a8abe85aa 100644 --- a/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.cs +++ b/src/Generated/Models/InternalCreateModerationRequestInputImageUrl.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationRequestInputImageUrl { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateModerationRequestInputImageUrl(string url) { Argument.AssertNotNull(url, nameof(url)); @@ -17,16 +19,18 @@ public InternalCreateModerationRequestInputImageUrl(string url) Url = url; } - internal InternalCreateModerationRequestInputImageUrl(string url, IDictionary serializedAdditionalRawData) + internal InternalCreateModerationRequestInputImageUrl(string url, IDictionary additionalBinaryDataProperties) { Url = url; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateModerationRequestInputImageUrl() + public string Url { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Url { get; } } } diff --git a/src/Generated/Models/InternalCreateModerationRequestModel.cs b/src/Generated/Models/InternalCreateModerationRequestModel.cs index 4d45c3a9f..9427eba80 100644 --- a/src/Generated/Models/InternalCreateModerationRequestModel.cs +++ b/src/Generated/Models/InternalCreateModerationRequestModel.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Moderations { internal readonly partial struct InternalCreateModerationRequestModel : IEquatable { private readonly string _value; - - public InternalCreateModerationRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string OmniModerationLatestValue = "omni-moderation-latest"; private const string OmniModeration20240926Value = "omni-moderation-2024-09-26"; private const string TextModerationLatestValue = "text-moderation-latest"; private const string TextModerationStableValue = "text-moderation-stable"; + public InternalCreateModerationRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateModerationRequestModel OmniModerationLatest { get; } = new InternalCreateModerationRequestModel(OmniModerationLatestValue); + public static InternalCreateModerationRequestModel OmniModeration20240926 { get; } = new InternalCreateModerationRequestModel(OmniModeration20240926Value); + public static InternalCreateModerationRequestModel TextModerationLatest { get; } = new InternalCreateModerationRequestModel(TextModerationLatestValue); + public static InternalCreateModerationRequestModel TextModerationStable { get; } = new InternalCreateModerationRequestModel(TextModerationStableValue); + public static bool operator ==(InternalCreateModerationRequestModel left, InternalCreateModerationRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateModerationRequestModel left, InternalCreateModerationRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateModerationRequestModel(string value) => new InternalCreateModerationRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateModerationRequestModel other && Equals(other); + public bool Equals(InternalCreateModerationRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.Serialization.cs b/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.Serialization.cs index 5468c79e5..7e26ddd19 100644 --- a/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.Serialization.cs +++ b/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.Serialization.cs @@ -7,153 +7,228 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalCreateModerationResponseResultCategoryAppliedInputTypes : IJsonModel { + internal InternalCreateModerationResponseResultCategoryAppliedInputTypes() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateModerationResponseResultCategoryAppliedInputTypes)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("hate") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate") != true) { writer.WritePropertyName("hate"u8); writer.WriteStartArray(); - foreach (var item in Hate) + foreach (string item in Hate) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("hate/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate/threatening") != true) { writer.WritePropertyName("hate/threatening"u8); writer.WriteStartArray(); - foreach (var item in HateThreatening) + foreach (string item in HateThreatening) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("harassment") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment") != true) { writer.WritePropertyName("harassment"u8); writer.WriteStartArray(); - foreach (var item in Harassment) + foreach (string item in Harassment) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("harassment/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment/threatening") != true) { writer.WritePropertyName("harassment/threatening"u8); writer.WriteStartArray(); - foreach (var item in HarassmentThreatening) + foreach (string item in HarassmentThreatening) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("illicit") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit") != true) { writer.WritePropertyName("illicit"u8); writer.WriteStartArray(); - foreach (var item in Illicit) + foreach (string item in Illicit) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("illicit/violent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit/violent") != true) { writer.WritePropertyName("illicit/violent"u8); writer.WriteStartArray(); - foreach (var item in IllicitViolent) + foreach (string item in IllicitViolent) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm") != true) { writer.WritePropertyName("self-harm"u8); writer.WriteStartArray(); - foreach (var item in SelfHarm) + foreach (string item in SelfHarm) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/intent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/intent") != true) { writer.WritePropertyName("self-harm/intent"u8); writer.WriteStartArray(); - foreach (var item in SelfHarmIntent) + foreach (string item in SelfHarmIntent) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/instructions") != true) { writer.WritePropertyName("self-harm/instructions"u8); writer.WriteStartArray(); - foreach (var item in SelfHarmInstructions) + foreach (string item in SelfHarmInstructions) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual") != true) { writer.WritePropertyName("sexual"u8); writer.WriteStartArray(); - foreach (var item in Sexual) + foreach (string item in Sexual) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("sexual/minors") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual/minors") != true) { writer.WritePropertyName("sexual/minors"u8); writer.WriteStartArray(); - foreach (var item in SexualMinors) + foreach (string item in SexualMinors) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence") != true) { writer.WritePropertyName("violence"u8); writer.WriteStartArray(); - foreach (var item in Violence) + foreach (string item in Violence) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("violence/graphic") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence/graphic") != true) { writer.WritePropertyName("violence/graphic"u8); writer.WriteStartArray(); - foreach (var item in ViolenceGraphic) + foreach (string item in ViolenceGraphic) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -161,7 +236,7 @@ void IJsonModel } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -170,25 +245,23 @@ void IJsonModel #endif } } - writer.WriteEndObject(); } - InternalCreateModerationResponseResultCategoryAppliedInputTypes IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateModerationResponseResultCategoryAppliedInputTypes IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateModerationResponseResultCategoryAppliedInputTypes JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateModerationResponseResultCategoryAppliedInputTypes)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(document.RootElement, options); } - internal static InternalCreateModerationResponseResultCategoryAppliedInputTypes DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateModerationResponseResultCategoryAppliedInputTypes DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -206,147 +279,235 @@ internal static InternalCreateModerationResponseResultCategoryAppliedInputTypes IReadOnlyList sexualMinors = default; IReadOnlyList violence = default; IReadOnlyList violenceGraphic = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("hate"u8)) + if (prop.NameEquals("hate"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } hate = array; continue; } - if (property.NameEquals("hate/threatening"u8)) + if (prop.NameEquals("hate/threatening"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } hateThreatening = array; continue; } - if (property.NameEquals("harassment"u8)) + if (prop.NameEquals("harassment"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } harassment = array; continue; } - if (property.NameEquals("harassment/threatening"u8)) + if (prop.NameEquals("harassment/threatening"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } harassmentThreatening = array; continue; } - if (property.NameEquals("illicit"u8)) + if (prop.NameEquals("illicit"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } illicit = array; continue; } - if (property.NameEquals("illicit/violent"u8)) + if (prop.NameEquals("illicit/violent"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } illicitViolent = array; continue; } - if (property.NameEquals("self-harm"u8)) + if (prop.NameEquals("self-harm"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } selfHarm = array; continue; } - if (property.NameEquals("self-harm/intent"u8)) + if (prop.NameEquals("self-harm/intent"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } selfHarmIntent = array; continue; } - if (property.NameEquals("self-harm/instructions"u8)) + if (prop.NameEquals("self-harm/instructions"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } selfHarmInstructions = array; continue; } - if (property.NameEquals("sexual"u8)) + if (prop.NameEquals("sexual"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } sexual = array; continue; } - if (property.NameEquals("sexual/minors"u8)) + if (prop.NameEquals("sexual/minors"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } sexualMinors = array; continue; } - if (property.NameEquals("violence"u8)) + if (prop.NameEquals("violence"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } violence = array; continue; } - if (property.NameEquals("violence/graphic"u8)) + if (prop.NameEquals("violence/graphic"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } violenceGraphic = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalCreateModerationResponseResultCategoryAppliedInputTypes( hate, hateThreatening, @@ -361,13 +522,14 @@ internal static InternalCreateModerationResponseResultCategoryAppliedInputTypes sexualMinors, violence, violenceGraphic, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -377,15 +539,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateModerationResponseResultCategoryAppliedInputTypes IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateModerationResponseResultCategoryAppliedInputTypes 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(document.RootElement, options); } default: @@ -395,15 +558,20 @@ InternalCreateModerationResponseResultCategoryAppliedInputTypes IPersistableMode string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateModerationResponseResultCategoryAppliedInputTypes FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateModerationResponseResultCategoryAppliedInputTypes internalCreateModerationResponseResultCategoryAppliedInputTypes) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(document.RootElement); + if (internalCreateModerationResponseResultCategoryAppliedInputTypes == null) + { + return null; + } + return BinaryContent.Create(internalCreateModerationResponseResultCategoryAppliedInputTypes, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateModerationResponseResultCategoryAppliedInputTypes(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateModerationResponseResultCategoryAppliedInputTypes(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.cs b/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.cs index 8669fed80..de743bfbc 100644 --- a/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.cs +++ b/src/Generated/Models/InternalCreateModerationResponseResultCategoryAppliedInputTypes.cs @@ -10,23 +10,10 @@ namespace OpenAI.Moderations { internal partial class InternalCreateModerationResponseResultCategoryAppliedInputTypes { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateModerationResponseResultCategoryAppliedInputTypes(IEnumerable hate, IEnumerable hateThreatening, IEnumerable harassment, IEnumerable harassmentThreatening, IEnumerable illicit, IEnumerable illicitViolent, IEnumerable selfHarm, IEnumerable selfHarmIntent, IEnumerable selfHarmInstructions, IEnumerable sexual, IEnumerable sexualMinors, IEnumerable violence, IEnumerable violenceGraphic) { - Argument.AssertNotNull(hate, nameof(hate)); - Argument.AssertNotNull(hateThreatening, nameof(hateThreatening)); - Argument.AssertNotNull(harassment, nameof(harassment)); - Argument.AssertNotNull(harassmentThreatening, nameof(harassmentThreatening)); - Argument.AssertNotNull(illicit, nameof(illicit)); - Argument.AssertNotNull(illicitViolent, nameof(illicitViolent)); - Argument.AssertNotNull(selfHarm, nameof(selfHarm)); - Argument.AssertNotNull(selfHarmIntent, nameof(selfHarmIntent)); - Argument.AssertNotNull(selfHarmInstructions, nameof(selfHarmInstructions)); - Argument.AssertNotNull(sexual, nameof(sexual)); - Argument.AssertNotNull(sexualMinors, nameof(sexualMinors)); - Argument.AssertNotNull(violence, nameof(violence)); - Argument.AssertNotNull(violenceGraphic, nameof(violenceGraphic)); - Hate = hate.ToList(); HateThreatening = hateThreatening.ToList(); Harassment = harassment.ToList(); @@ -42,7 +29,7 @@ internal InternalCreateModerationResponseResultCategoryAppliedInputTypes(IEnumer ViolenceGraphic = violenceGraphic.ToList(); } - internal InternalCreateModerationResponseResultCategoryAppliedInputTypes(IReadOnlyList hate, IReadOnlyList hateThreatening, IReadOnlyList harassment, IReadOnlyList harassmentThreatening, IReadOnlyList illicit, IReadOnlyList illicitViolent, IReadOnlyList selfHarm, IReadOnlyList selfHarmIntent, IReadOnlyList selfHarmInstructions, IReadOnlyList sexual, IReadOnlyList sexualMinors, IReadOnlyList violence, IReadOnlyList violenceGraphic, IDictionary serializedAdditionalRawData) + internal InternalCreateModerationResponseResultCategoryAppliedInputTypes(IReadOnlyList hate, IReadOnlyList hateThreatening, IReadOnlyList harassment, IReadOnlyList harassmentThreatening, IReadOnlyList illicit, IReadOnlyList illicitViolent, IReadOnlyList selfHarm, IReadOnlyList selfHarmIntent, IReadOnlyList selfHarmInstructions, IReadOnlyList sexual, IReadOnlyList sexualMinors, IReadOnlyList violence, IReadOnlyList violenceGraphic, IDictionary additionalBinaryDataProperties) { Hate = hate; HateThreatening = hateThreatening; @@ -57,11 +44,13 @@ internal InternalCreateModerationResponseResultCategoryAppliedInputTypes(IReadOn SexualMinors = sexualMinors; Violence = violence; ViolenceGraphic = violenceGraphic; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateModerationResponseResultCategoryAppliedInputTypes() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/InternalCreateRunRequestModel.cs b/src/Generated/Models/InternalCreateRunRequestModel.cs index 27b73a31b..71afae71b 100644 --- a/src/Generated/Models/InternalCreateRunRequestModel.cs +++ b/src/Generated/Models/InternalCreateRunRequestModel.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalCreateRunRequestModel : IEquatable { private readonly string _value; - - public InternalCreateRunRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string Gpt4oValue = "gpt-4o"; private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; @@ -40,39 +35,73 @@ public InternalCreateRunRequestModel(string value) private const string Gpt35Turbo0125Value = "gpt-3.5-turbo-0125"; private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; + public InternalCreateRunRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateRunRequestModel Gpt4o { get; } = new InternalCreateRunRequestModel(Gpt4oValue); + public static InternalCreateRunRequestModel Gpt4o20240806 { get; } = new InternalCreateRunRequestModel(Gpt4o20240806Value); + public static InternalCreateRunRequestModel Gpt4o20240513 { get; } = new InternalCreateRunRequestModel(Gpt4o20240513Value); + public static InternalCreateRunRequestModel Gpt4oMini { get; } = new InternalCreateRunRequestModel(Gpt4oMiniValue); + public static InternalCreateRunRequestModel Gpt4oMini20240718 { get; } = new InternalCreateRunRequestModel(Gpt4oMini20240718Value); + public static InternalCreateRunRequestModel Gpt4Turbo { get; } = new InternalCreateRunRequestModel(Gpt4TurboValue); + public static InternalCreateRunRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateRunRequestModel(Gpt4Turbo20240409Value); + public static InternalCreateRunRequestModel Gpt40125Preview { get; } = new InternalCreateRunRequestModel(Gpt40125PreviewValue); + public static InternalCreateRunRequestModel Gpt4TurboPreview { get; } = new InternalCreateRunRequestModel(Gpt4TurboPreviewValue); + public static InternalCreateRunRequestModel Gpt41106Preview { get; } = new InternalCreateRunRequestModel(Gpt41106PreviewValue); + public static InternalCreateRunRequestModel Gpt4VisionPreview { get; } = new InternalCreateRunRequestModel(Gpt4VisionPreviewValue); + public static InternalCreateRunRequestModel Gpt4 { get; } = new InternalCreateRunRequestModel(Gpt4Value); + public static InternalCreateRunRequestModel Gpt40314 { get; } = new InternalCreateRunRequestModel(Gpt40314Value); + public static InternalCreateRunRequestModel Gpt40613 { get; } = new InternalCreateRunRequestModel(Gpt40613Value); + public static InternalCreateRunRequestModel Gpt432k { get; } = new InternalCreateRunRequestModel(Gpt432kValue); + public static InternalCreateRunRequestModel Gpt432k0314 { get; } = new InternalCreateRunRequestModel(Gpt432k0314Value); + public static InternalCreateRunRequestModel Gpt432k0613 { get; } = new InternalCreateRunRequestModel(Gpt432k0613Value); + public static InternalCreateRunRequestModel Gpt35Turbo { get; } = new InternalCreateRunRequestModel(Gpt35TurboValue); + public static InternalCreateRunRequestModel Gpt35Turbo16k { get; } = new InternalCreateRunRequestModel(Gpt35Turbo16kValue); + public static InternalCreateRunRequestModel Gpt35Turbo0613 { get; } = new InternalCreateRunRequestModel(Gpt35Turbo0613Value); + public static InternalCreateRunRequestModel Gpt35Turbo1106 { get; } = new InternalCreateRunRequestModel(Gpt35Turbo1106Value); + public static InternalCreateRunRequestModel Gpt35Turbo0125 { get; } = new InternalCreateRunRequestModel(Gpt35Turbo0125Value); + public static InternalCreateRunRequestModel Gpt35Turbo16k0613 { get; } = new InternalCreateRunRequestModel(Gpt35Turbo16k0613Value); + public static bool operator ==(InternalCreateRunRequestModel left, InternalCreateRunRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateRunRequestModel left, InternalCreateRunRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateRunRequestModel(string value) => new InternalCreateRunRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateRunRequestModel other && Equals(other); + public bool Equals(InternalCreateRunRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateSpeechRequestModel.cs b/src/Generated/Models/InternalCreateSpeechRequestModel.cs index 795344fd1..8c9149261 100644 --- a/src/Generated/Models/InternalCreateSpeechRequestModel.cs +++ b/src/Generated/Models/InternalCreateSpeechRequestModel.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateSpeechRequestModel : IEquatable { private readonly string _value; + private const string Tts1Value = "tts-1"; + private const string Tts1HdValue = "tts-1-hd"; public InternalCreateSpeechRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Tts1Value = "tts-1"; - private const string Tts1HdValue = "tts-1-hd"; + _value = value; + } public static InternalCreateSpeechRequestModel Tts1 { get; } = new InternalCreateSpeechRequestModel(Tts1Value); + public static InternalCreateSpeechRequestModel Tts1Hd { get; } = new InternalCreateSpeechRequestModel(Tts1HdValue); + public static bool operator ==(InternalCreateSpeechRequestModel left, InternalCreateSpeechRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateSpeechRequestModel left, InternalCreateSpeechRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateSpeechRequestModel(string value) => new InternalCreateSpeechRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateSpeechRequestModel other && Equals(other); + public bool Equals(InternalCreateSpeechRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequest.Serialization.cs b/src/Generated/Models/InternalCreateThreadAndRunRequest.Serialization.cs index 20185da5d..471899a6b 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequest.Serialization.cs @@ -7,43 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalCreateThreadAndRunRequest : IJsonModel { + internal InternalCreateThreadAndRunRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadAndRunRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("assistant_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (SerializedAdditionalRawData?.ContainsKey("thread") != true && Optional.IsDefined(Thread)) + if (Optional.IsDefined(Thread) && _additionalBinaryDataProperties?.ContainsKey("thread") != true) { writer.WritePropertyName("thread"u8); writer.WriteObjectValue(Thread, options); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) - { - if (Model != null) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); - } - else - { - writer.WriteNull("model"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(Instructions)) + if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { if (Instructions != null) { @@ -52,16 +50,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("instructions"); + writer.WriteNull("instructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { if (Tools != null) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ToolDefinition item in Tools) { writer.WriteObjectValue(item, options); } @@ -69,22 +67,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("tools"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) - { - if (ToolResources != null) - { - writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); - } - else - { - writer.WriteNull("tool_resources"); + writer.WriteNull("tools"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -93,16 +79,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -111,10 +102,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(TopP)) + if (Optional.IsDefined(TopP) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { if (TopP != null) { @@ -123,10 +114,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("top_p"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("stream") != true && Optional.IsDefined(Stream)) + if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true) { if (Stream != null) { @@ -135,10 +126,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("stream"); + writer.WriteNull("stream"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_prompt_tokens") != true && Optional.IsDefined(MaxPromptTokens)) + if (Optional.IsDefined(MaxPromptTokens) && _additionalBinaryDataProperties?.ContainsKey("max_prompt_tokens") != true) { if (MaxPromptTokens != null) { @@ -147,10 +138,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("max_prompt_tokens"); + writer.WriteNull("maxPromptTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_completion_tokens") != true && Optional.IsDefined(MaxCompletionTokens)) + if (Optional.IsDefined(MaxCompletionTokens) && _additionalBinaryDataProperties?.ContainsKey("max_completion_tokens") != true) { if (MaxCompletionTokens != null) { @@ -159,10 +150,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("max_completion_tokens"); + writer.WriteNull("maxCompletionTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("truncation_strategy") != true && Optional.IsDefined(TruncationStrategy)) + if (Optional.IsDefined(TruncationStrategy) && _additionalBinaryDataProperties?.ContainsKey("truncation_strategy") != true) { if (TruncationStrategy != null) { @@ -171,27 +162,39 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("truncation_strategy"); + writer.WriteNull("truncationStrategy"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true && Optional.IsDefined(ToolChoice)) + if (Optional.IsDefined(ParallelToolCalls) && _additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true) { - if (ToolChoice != null) + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) + { + if (Model != null) { - writer.WritePropertyName("tool_choice"u8); - writer.WriteObjectValue(ToolChoice, options); + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); } else { - writer.WriteNull("tool_choice"); + writer.WriteNull("model"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(ParallelToolCalls)) + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) { - writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(ParallelToolCalls.Value); + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("toolResources"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) { if (ResponseFormat != null) { @@ -200,12 +203,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, } else { - writer.WriteNull("response_format"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(ToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { - foreach (var item in SerializedAdditionalRawData) + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); + writer.WriteObjectValue(ToolChoice, options); + } + else + { + writer.WriteNull("toolChoice"u8); + } + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -213,7 +228,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -222,35 +237,31 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - InternalCreateThreadAndRunRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadAndRunRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadAndRunRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadAndRunRequest(document.RootElement, options); } - internal static InternalCreateThreadAndRunRequest DeserializeInternalCreateThreadAndRunRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadAndRunRequest DeserializeInternalCreateThreadAndRunRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string assistantId = default; ThreadCreationOptions thread = default; - string model = default; string instructions = default; IList tools = default; - ToolResources toolResources = default; IDictionary metadata = default; float? temperature = default; float? topP = default; @@ -258,188 +269,192 @@ internal static InternalCreateThreadAndRunRequest DeserializeInternalCreateThrea int? maxPromptTokens = default; int? maxCompletionTokens = default; RunTruncationStrategy truncationStrategy = default; - ToolConstraint toolChoice = default; bool? parallelToolCalls = default; + string model = default; + ToolResources toolResources = default; AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ToolConstraint toolChoice = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("assistant_id"u8)) - { - assistantId = property.Value.GetString(); - continue; - } - if (property.NameEquals("thread"u8)) + if (prop.NameEquals("assistant_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - thread = ThreadCreationOptions.DeserializeThreadCreationOptions(property.Value, options); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("thread"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - model = null; continue; } - model = property.Value.GetString(); + thread = ThreadCreationOptions.DeserializeThreadCreationOptions(prop.Value, options); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { instructions = null; continue; } - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); } tools = array; continue; } - if (property.NameEquals("tool_resources"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - toolResources = null; - continue; - } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); - continue; - } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { temperature = null; continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { topP = null; continue; } - topP = property.Value.GetSingle(); + topP = prop.Value.GetSingle(); continue; } - if (property.NameEquals("stream"u8)) + if (prop.NameEquals("stream"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { stream = null; continue; } - stream = property.Value.GetBoolean(); + stream = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("max_prompt_tokens"u8)) + if (prop.NameEquals("max_prompt_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { maxPromptTokens = null; continue; } - maxPromptTokens = property.Value.GetInt32(); + maxPromptTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("max_completion_tokens"u8)) + if (prop.NameEquals("max_completion_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { maxCompletionTokens = null; continue; } - maxCompletionTokens = property.Value.GetInt32(); + maxCompletionTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("truncation_strategy"u8)) + if (prop.NameEquals("truncation_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { truncationStrategy = null; continue; } - truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(property.Value, options); + truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(prop.Value, options); continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("parallel_tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolChoice = null; continue; } - toolChoice = ToolConstraint.DeserializeToolConstraint(property.Value, options); + parallelToolCalls = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("parallel_tool_calls"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + model = null; continue; } - parallelToolCalls = property.Value.GetBoolean(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); + continue; + } + if (prop.NameEquals("response_format"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { responseFormat = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); + continue; + } + if (prop.NameEquals("tool_choice"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = ToolConstraint.DeserializeToolConstraint(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalCreateThreadAndRunRequest( assistantId, thread, - model, instructions, tools ?? new ChangeTrackingList(), - toolResources, metadata ?? new ChangeTrackingDictionary(), temperature, topP, @@ -447,16 +462,19 @@ internal static InternalCreateThreadAndRunRequest DeserializeInternalCreateThrea maxPromptTokens, maxCompletionTokens, truncationStrategy, - toolChoice, parallelToolCalls, + model, + toolResources, responseFormat, - serializedAdditionalRawData); + toolChoice, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -466,15 +484,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - InternalCreateThreadAndRunRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadAndRunRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadAndRunRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadAndRunRequest(document.RootElement, options); } default: @@ -484,15 +503,20 @@ InternalCreateThreadAndRunRequest IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadAndRunRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadAndRunRequest internalCreateThreadAndRunRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadAndRunRequest(document.RootElement); + if (internalCreateThreadAndRunRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadAndRunRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadAndRunRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadAndRunRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequest.cs b/src/Generated/Models/InternalCreateThreadAndRunRequest.cs index 5e50cf643..77bb26a64 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequest.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequest.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalCreateThreadAndRunRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadAndRunRequest(string assistantId) { Argument.AssertNotNull(assistantId, nameof(assistantId)); @@ -19,14 +21,12 @@ public InternalCreateThreadAndRunRequest(string assistantId) Metadata = new ChangeTrackingDictionary(); } - internal InternalCreateThreadAndRunRequest(string assistantId, ThreadCreationOptions thread, string model, string instructions, IList tools, ToolResources toolResources, IDictionary metadata, float? temperature, float? topP, bool? stream, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolChoice, bool? parallelToolCalls, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadAndRunRequest(string assistantId, ThreadCreationOptions thread, string instructions, IList tools, IDictionary metadata, float? temperature, float? topP, bool? stream, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, bool? parallelToolCalls, string model, ToolResources toolResources, AssistantResponseFormat responseFormat, ToolConstraint toolChoice, IDictionary additionalBinaryDataProperties) { AssistantId = assistantId; Thread = thread; - Model = model; Instructions = instructions; Tools = tools; - ToolResources = toolResources; Metadata = metadata; Temperature = temperature; TopP = topP; @@ -34,27 +34,42 @@ internal InternalCreateThreadAndRunRequest(string assistantId, ThreadCreationOpt MaxPromptTokens = maxPromptTokens; MaxCompletionTokens = maxCompletionTokens; TruncationStrategy = truncationStrategy; - ToolChoice = toolChoice; ParallelToolCalls = parallelToolCalls; + Model = model; + ToolResources = toolResources; ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateThreadAndRunRequest() - { + ToolChoice = toolChoice; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string AssistantId { get; } + public ThreadCreationOptions Thread { get; set; } + public string Instructions { get; set; } + public IList Tools { get; set; } + public IDictionary Metadata { get; set; } + public float? Temperature { get; set; } + public float? TopP { get; set; } + public bool? Stream { get; set; } + public int? MaxPromptTokens { get; set; } + public int? MaxCompletionTokens { get; set; } + public RunTruncationStrategy TruncationStrategy { get; set; } + public bool? ParallelToolCalls { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs index 04d84a623..35e576c4a 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestModel.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalCreateThreadAndRunRequestModel : IEquatable { private readonly string _value; - - public InternalCreateThreadAndRunRequestModel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string Gpt4oValue = "gpt-4o"; private const string Gpt4o20240806Value = "gpt-4o-2024-08-06"; private const string Gpt4o20240513Value = "gpt-4o-2024-05-13"; @@ -40,39 +35,73 @@ public InternalCreateThreadAndRunRequestModel(string value) private const string Gpt35Turbo0125Value = "gpt-3.5-turbo-0125"; private const string Gpt35Turbo16k0613Value = "gpt-3.5-turbo-16k-0613"; + public InternalCreateThreadAndRunRequestModel(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateThreadAndRunRequestModel Gpt4o { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oValue); + public static InternalCreateThreadAndRunRequestModel Gpt4o20240806 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4o20240806Value); + public static InternalCreateThreadAndRunRequestModel Gpt4o20240513 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4o20240513Value); + public static InternalCreateThreadAndRunRequestModel Gpt4oMini { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oMiniValue); + public static InternalCreateThreadAndRunRequestModel Gpt4oMini20240718 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4oMini20240718Value); + public static InternalCreateThreadAndRunRequestModel Gpt4Turbo { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4TurboValue); + public static InternalCreateThreadAndRunRequestModel Gpt4Turbo20240409 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4Turbo20240409Value); + public static InternalCreateThreadAndRunRequestModel Gpt40125Preview { get; } = new InternalCreateThreadAndRunRequestModel(Gpt40125PreviewValue); + public static InternalCreateThreadAndRunRequestModel Gpt4TurboPreview { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4TurboPreviewValue); + public static InternalCreateThreadAndRunRequestModel Gpt41106Preview { get; } = new InternalCreateThreadAndRunRequestModel(Gpt41106PreviewValue); + public static InternalCreateThreadAndRunRequestModel Gpt4VisionPreview { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4VisionPreviewValue); + public static InternalCreateThreadAndRunRequestModel Gpt4 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt4Value); + public static InternalCreateThreadAndRunRequestModel Gpt40314 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt40314Value); + public static InternalCreateThreadAndRunRequestModel Gpt40613 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt40613Value); + public static InternalCreateThreadAndRunRequestModel Gpt432k { get; } = new InternalCreateThreadAndRunRequestModel(Gpt432kValue); + public static InternalCreateThreadAndRunRequestModel Gpt432k0314 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt432k0314Value); + public static InternalCreateThreadAndRunRequestModel Gpt432k0613 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt432k0613Value); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35TurboValue); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo16k { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35Turbo16kValue); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo0613 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35Turbo0613Value); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo1106 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35Turbo1106Value); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo0125 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35Turbo0125Value); + public static InternalCreateThreadAndRunRequestModel Gpt35Turbo16k0613 { get; } = new InternalCreateThreadAndRunRequestModel(Gpt35Turbo16k0613Value); + public static bool operator ==(InternalCreateThreadAndRunRequestModel left, InternalCreateThreadAndRunRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateThreadAndRunRequestModel left, InternalCreateThreadAndRunRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateThreadAndRunRequestModel(string value) => new InternalCreateThreadAndRunRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateThreadAndRunRequestModel other && Equals(other); + public bool Equals(InternalCreateThreadAndRunRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestToolChoice.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestToolChoice.cs index 45a467b3c..439d3b7fc 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestToolChoice.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestToolChoice.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalCreateThreadAndRunRequestToolChoice : IEquatable { private readonly string _value; + private const string NoneValue = "none"; + private const string AutoValue = "auto"; + private const string RequiredValue = "required"; public InternalCreateThreadAndRunRequestToolChoice(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string NoneValue = "none"; - private const string AutoValue = "auto"; - private const string RequiredValue = "required"; + _value = value; + } public static InternalCreateThreadAndRunRequestToolChoice None { get; } = new InternalCreateThreadAndRunRequestToolChoice(NoneValue); + public static InternalCreateThreadAndRunRequestToolChoice Auto { get; } = new InternalCreateThreadAndRunRequestToolChoice(AutoValue); + public static InternalCreateThreadAndRunRequestToolChoice Required { get; } = new InternalCreateThreadAndRunRequestToolChoice(RequiredValue); + public static bool operator ==(InternalCreateThreadAndRunRequestToolChoice left, InternalCreateThreadAndRunRequestToolChoice right) => left.Equals(right); + public static bool operator !=(InternalCreateThreadAndRunRequestToolChoice left, InternalCreateThreadAndRunRequestToolChoice right) => !left.Equals(right); + public static implicit operator InternalCreateThreadAndRunRequestToolChoice(string value) => new InternalCreateThreadAndRunRequestToolChoice(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateThreadAndRunRequestToolChoice other && Equals(other); + public bool Equals(InternalCreateThreadAndRunRequestToolChoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs index aff6e9e50..ded12e75f 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalCreateThreadAndRunRequestToolResources : IJsonMod { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadAndRunRequestToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWr #endif } } - writer.WriteEndObject(); } - InternalCreateThreadAndRunRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadAndRunRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadAndRunRequestToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadAndRunRequestToolResources(document.RootElement, options); } - internal static InternalCreateThreadAndRunRequestToolResources DeserializeInternalCreateThreadAndRunRequestToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadAndRunRequestToolResources DeserializeInternalCreateThreadAndRunRequestToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter = default; InternalToolResourcesFileSearchIdsOnly fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadAndRunRequestToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalCreateThreadAndRunRequestToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Wri } } - InternalCreateThreadAndRunRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadAndRunRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadAndRunRequestToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadAndRunRequestToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalCreateThreadAndRunRequestToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadAndRunRequestToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadAndRunRequestToolResources internalCreateThreadAndRunRequestToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadAndRunRequestToolResources(document.RootElement); + if (internalCreateThreadAndRunRequestToolResources == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadAndRunRequestToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadAndRunRequestToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadAndRunRequestToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs index a07a484a3..08726ec52 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalCreateThreadAndRunRequestToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadAndRunRequestToolResources() { } - internal InternalCreateThreadAndRunRequestToolResources(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadAndRunRequestToolResources(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.Serialization.cs index 73c8d2c30..141e218cd 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalCreateThreadAndRunRequestToolResourcesCodeInterpr { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.W } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.W #endif } } - writer.WriteEndObject(); } - InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter IPersistableModel< string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter internalCreateThreadAndRunRequestToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(document.RootElement); + if (internalCreateThreadAndRunRequestToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadAndRunRequestToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.cs index ed362ab6b..d48dfdb72 100644 --- a/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs b/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs index 39b6689b2..b9e1a4ee7 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalCreateThreadRequestToolResources : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadRequestToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter w } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWriter w #endif } } - writer.WriteEndObject(); } - InternalCreateThreadRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadRequestToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadRequestToolResources(document.RootElement, options); } - internal static InternalCreateThreadRequestToolResources DeserializeInternalCreateThreadRequestToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadRequestToolResources DeserializeInternalCreateThreadRequestToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter = default; FileSearchToolResources fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalCreateThreadRequestToolResourcesCodeInterpreter.DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalCreateThreadRequestToolResourcesCodeInterpreter.DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(property.Value, options); + fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalCreateThreadRequestToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalCreateThreadRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadRequestToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadRequestToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalCreateThreadRequestToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadRequestToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadRequestToolResources internalCreateThreadRequestToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResources(document.RootElement); + if (internalCreateThreadRequestToolResources == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadRequestToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadRequestToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadRequestToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResources.cs b/src/Generated/Models/InternalCreateThreadRequestToolResources.cs index 08a68fce1..f13e765c6 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResources.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalCreateThreadRequestToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadRequestToolResources() { } - internal InternalCreateThreadRequestToolResources(InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadRequestToolResources(InternalCreateThreadRequestToolResourcesCodeInterpreter codeInterpreter, FileSearchToolResources fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalCreateThreadRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } + public FileSearchToolResources FileSearch { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.Serialization.cs index 55825459e..1e6146b9e 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalCreateThreadRequestToolResourcesCodeInterpreter : { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadRequestToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(U } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(U #endif } } - writer.WriteEndObject(); } - InternalCreateThreadRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadRequestToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalCreateThreadRequestToolResourcesCodeInterpreter DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadRequestToolResourcesCodeInterpreter DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalCreateThreadRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadRequestToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadRequestToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalCreateThreadRequestToolResourcesCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadRequestToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadRequestToolResourcesCodeInterpreter internalCreateThreadRequestToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(document.RootElement); + if (internalCreateThreadRequestToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadRequestToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadRequestToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadRequestToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.cs index df61d7ce5..af5286bc4 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalCreateThreadRequestToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadRequestToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalCreateThreadRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary serializedAdditionalRawData) + internal InternalCreateThreadRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.Serialization.cs b/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.Serialization.cs index bc7fd659d..e432b91e0 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.Serialization.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,16 +15,21 @@ internal partial class InternalCreateThreadRequestToolResourcesFileSearchBase : { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateThreadRequestToolResourcesFileSearchBase)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -31,7 +37,7 @@ void IJsonModel.Write(Ut } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -40,47 +46,43 @@ void IJsonModel.Write(Ut #endif } } - writer.WriteEndObject(); } - InternalCreateThreadRequestToolResourcesFileSearchBase IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateThreadRequestToolResourcesFileSearchBase IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateThreadRequestToolResourcesFileSearchBase JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateThreadRequestToolResourcesFileSearchBase)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(document.RootElement, options); } - internal static InternalCreateThreadRequestToolResourcesFileSearchBase DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateThreadRequestToolResourcesFileSearchBase DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateThreadRequestToolResourcesFileSearchBase(serializedAdditionalRawData); + return new InternalCreateThreadRequestToolResourcesFileSearchBase(additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -90,15 +92,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateThreadRequestToolResourcesFileSearchBase IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateThreadRequestToolResourcesFileSearchBase 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(document.RootElement, options); } default: @@ -108,15 +111,20 @@ InternalCreateThreadRequestToolResourcesFileSearchBase IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateThreadRequestToolResourcesFileSearchBase FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateThreadRequestToolResourcesFileSearchBase internalCreateThreadRequestToolResourcesFileSearchBase) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(document.RootElement); + if (internalCreateThreadRequestToolResourcesFileSearchBase == null) + { + return null; + } + return BinaryContent.Create(internalCreateThreadRequestToolResourcesFileSearchBase, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateThreadRequestToolResourcesFileSearchBase(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateThreadRequestToolResourcesFileSearchBase(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.cs b/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.cs index 4a84b73f5..be6327344 100644 --- a/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.cs +++ b/src/Generated/Models/InternalCreateThreadRequestToolResourcesFileSearchBase.cs @@ -9,14 +9,21 @@ namespace OpenAI.Assistants { internal partial class InternalCreateThreadRequestToolResourcesFileSearchBase { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateThreadRequestToolResourcesFileSearchBase() { } - internal InternalCreateThreadRequestToolResourcesFileSearchBase(IDictionary serializedAdditionalRawData) + internal InternalCreateThreadRequestToolResourcesFileSearchBase(IDictionary additionalBinaryDataProperties) + { + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData { - SerializedAdditionalRawData = serializedAdditionalRawData; + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/InternalCreateTranscriptionRequestModel.cs b/src/Generated/Models/InternalCreateTranscriptionRequestModel.cs index a04004f24..783ab0bcf 100644 --- a/src/Generated/Models/InternalCreateTranscriptionRequestModel.cs +++ b/src/Generated/Models/InternalCreateTranscriptionRequestModel.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateTranscriptionRequestModel : IEquatable { private readonly string _value; + private const string Whisper1Value = "whisper-1"; public InternalCreateTranscriptionRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Whisper1Value = "whisper-1"; + _value = value; + } public static InternalCreateTranscriptionRequestModel Whisper1 { get; } = new InternalCreateTranscriptionRequestModel(Whisper1Value); + public static bool operator ==(InternalCreateTranscriptionRequestModel left, InternalCreateTranscriptionRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateTranscriptionRequestModel left, InternalCreateTranscriptionRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateTranscriptionRequestModel(string value) => new InternalCreateTranscriptionRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateTranscriptionRequestModel other && Equals(other); + public bool Equals(InternalCreateTranscriptionRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateTranscriptionRequestTimestampGranularities.cs b/src/Generated/Models/InternalCreateTranscriptionRequestTimestampGranularities.cs index 62d12e98b..f5153c185 100644 --- a/src/Generated/Models/InternalCreateTranscriptionRequestTimestampGranularities.cs +++ b/src/Generated/Models/InternalCreateTranscriptionRequestTimestampGranularities.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateTranscriptionRequestTimestampGranularities : IEquatable { private readonly string _value; + private const string WordValue = "word"; + private const string SegmentValue = "segment"; public InternalCreateTranscriptionRequestTimestampGranularities(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string WordValue = "word"; - private const string SegmentValue = "segment"; + _value = value; + } public static InternalCreateTranscriptionRequestTimestampGranularities Word { get; } = new InternalCreateTranscriptionRequestTimestampGranularities(WordValue); + public static InternalCreateTranscriptionRequestTimestampGranularities Segment { get; } = new InternalCreateTranscriptionRequestTimestampGranularities(SegmentValue); + public static bool operator ==(InternalCreateTranscriptionRequestTimestampGranularities left, InternalCreateTranscriptionRequestTimestampGranularities right) => left.Equals(right); + public static bool operator !=(InternalCreateTranscriptionRequestTimestampGranularities left, InternalCreateTranscriptionRequestTimestampGranularities right) => !left.Equals(right); + public static implicit operator InternalCreateTranscriptionRequestTimestampGranularities(string value) => new InternalCreateTranscriptionRequestTimestampGranularities(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateTranscriptionRequestTimestampGranularities other && Equals(other); + public bool Equals(InternalCreateTranscriptionRequestTimestampGranularities other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateTranscriptionResponseJson.Serialization.cs b/src/Generated/Models/InternalCreateTranscriptionResponseJson.Serialization.cs index a5e4863a8..14ed7a98e 100644 --- a/src/Generated/Models/InternalCreateTranscriptionResponseJson.Serialization.cs +++ b/src/Generated/Models/InternalCreateTranscriptionResponseJson.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { internal partial class InternalCreateTranscriptionResponseJson : IJsonModel { + internal InternalCreateTranscriptionResponseJson() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateTranscriptionResponseJson)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter wr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter wr #endif } } - writer.WriteEndObject(); } - InternalCreateTranscriptionResponseJson IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateTranscriptionResponseJson IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateTranscriptionResponseJson JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateTranscriptionResponseJson)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateTranscriptionResponseJson(document.RootElement, options); } - internal static InternalCreateTranscriptionResponseJson DeserializeInternalCreateTranscriptionResponseJson(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateTranscriptionResponseJson DeserializeInternalCreateTranscriptionResponseJson(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateTranscriptionResponseJson(text, serializedAdditionalRawData); + return new InternalCreateTranscriptionResponseJson(text, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalCreateTranscriptionResponseJson IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateTranscriptionResponseJson IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateTranscriptionResponseJson 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateTranscriptionResponseJson(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalCreateTranscriptionResponseJson IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateTranscriptionResponseJson FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateTranscriptionResponseJson internalCreateTranscriptionResponseJson) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateTranscriptionResponseJson(document.RootElement); + if (internalCreateTranscriptionResponseJson == null) + { + return null; + } + return BinaryContent.Create(internalCreateTranscriptionResponseJson, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateTranscriptionResponseJson(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateTranscriptionResponseJson(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateTranscriptionResponseJson.cs b/src/Generated/Models/InternalCreateTranscriptionResponseJson.cs index 19818f1d1..0e765561d 100644 --- a/src/Generated/Models/InternalCreateTranscriptionResponseJson.cs +++ b/src/Generated/Models/InternalCreateTranscriptionResponseJson.cs @@ -9,24 +9,25 @@ namespace OpenAI.Audio { internal partial class InternalCreateTranscriptionResponseJson { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateTranscriptionResponseJson(string text) { - Argument.AssertNotNull(text, nameof(text)); - Text = text; } - internal InternalCreateTranscriptionResponseJson(string text, IDictionary serializedAdditionalRawData) + internal InternalCreateTranscriptionResponseJson(string text, IDictionary additionalBinaryDataProperties) { Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateTranscriptionResponseJson() + public string Text { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Text { get; } } } diff --git a/src/Generated/Models/InternalCreateTranscriptionResponseVerboseJsonTask.cs b/src/Generated/Models/InternalCreateTranscriptionResponseVerboseJsonTask.cs index a94a2f567..5d3c06858 100644 --- a/src/Generated/Models/InternalCreateTranscriptionResponseVerboseJsonTask.cs +++ b/src/Generated/Models/InternalCreateTranscriptionResponseVerboseJsonTask.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateTranscriptionResponseVerboseJsonTask : IEquatable { private readonly string _value; + private const string TranscribeValue = "transcribe"; public InternalCreateTranscriptionResponseVerboseJsonTask(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TranscribeValue = "transcribe"; + _value = value; + } public static InternalCreateTranscriptionResponseVerboseJsonTask Transcribe { get; } = new InternalCreateTranscriptionResponseVerboseJsonTask(TranscribeValue); + public static bool operator ==(InternalCreateTranscriptionResponseVerboseJsonTask left, InternalCreateTranscriptionResponseVerboseJsonTask right) => left.Equals(right); + public static bool operator !=(InternalCreateTranscriptionResponseVerboseJsonTask left, InternalCreateTranscriptionResponseVerboseJsonTask right) => !left.Equals(right); + public static implicit operator InternalCreateTranscriptionResponseVerboseJsonTask(string value) => new InternalCreateTranscriptionResponseVerboseJsonTask(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateTranscriptionResponseVerboseJsonTask other && Equals(other); + public bool Equals(InternalCreateTranscriptionResponseVerboseJsonTask other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateTranslationRequestModel.cs b/src/Generated/Models/InternalCreateTranslationRequestModel.cs index 67effb4f6..f83ea19bc 100644 --- a/src/Generated/Models/InternalCreateTranslationRequestModel.cs +++ b/src/Generated/Models/InternalCreateTranslationRequestModel.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateTranslationRequestModel : IEquatable { private readonly string _value; + private const string Whisper1Value = "whisper-1"; public InternalCreateTranslationRequestModel(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Whisper1Value = "whisper-1"; + _value = value; + } public static InternalCreateTranslationRequestModel Whisper1 { get; } = new InternalCreateTranslationRequestModel(Whisper1Value); + public static bool operator ==(InternalCreateTranslationRequestModel left, InternalCreateTranslationRequestModel right) => left.Equals(right); + public static bool operator !=(InternalCreateTranslationRequestModel left, InternalCreateTranslationRequestModel right) => !left.Equals(right); + public static implicit operator InternalCreateTranslationRequestModel(string value) => new InternalCreateTranslationRequestModel(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateTranslationRequestModel other && Equals(other); + public bool Equals(InternalCreateTranslationRequestModel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateTranslationResponseJson.Serialization.cs b/src/Generated/Models/InternalCreateTranslationResponseJson.Serialization.cs index d0d1fcd37..ddaff2f1a 100644 --- a/src/Generated/Models/InternalCreateTranslationResponseJson.Serialization.cs +++ b/src/Generated/Models/InternalCreateTranslationResponseJson.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { internal partial class InternalCreateTranslationResponseJson : IJsonModel { + internal InternalCreateTranslationResponseJson() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateTranslationResponseJson)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalCreateTranslationResponseJson IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateTranslationResponseJson IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateTranslationResponseJson JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateTranslationResponseJson)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateTranslationResponseJson(document.RootElement, options); } - internal static InternalCreateTranslationResponseJson DeserializeInternalCreateTranslationResponseJson(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateTranslationResponseJson DeserializeInternalCreateTranslationResponseJson(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + text = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateTranslationResponseJson(text, serializedAdditionalRawData); + return new InternalCreateTranslationResponseJson(text, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalCreateTranslationResponseJson IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateTranslationResponseJson IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateTranslationResponseJson 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateTranslationResponseJson(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalCreateTranslationResponseJson IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateTranslationResponseJson FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateTranslationResponseJson internalCreateTranslationResponseJson) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateTranslationResponseJson(document.RootElement); + if (internalCreateTranslationResponseJson == null) + { + return null; + } + return BinaryContent.Create(internalCreateTranslationResponseJson, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateTranslationResponseJson(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateTranslationResponseJson(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateTranslationResponseJson.cs b/src/Generated/Models/InternalCreateTranslationResponseJson.cs index e6e9dae14..c72d3c914 100644 --- a/src/Generated/Models/InternalCreateTranslationResponseJson.cs +++ b/src/Generated/Models/InternalCreateTranslationResponseJson.cs @@ -9,24 +9,25 @@ namespace OpenAI.Audio { internal partial class InternalCreateTranslationResponseJson { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalCreateTranslationResponseJson(string text) { - Argument.AssertNotNull(text, nameof(text)); - Text = text; } - internal InternalCreateTranslationResponseJson(string text, IDictionary serializedAdditionalRawData) + internal InternalCreateTranslationResponseJson(string text, IDictionary additionalBinaryDataProperties) { Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateTranslationResponseJson() + public string Text { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Text { get; } } } diff --git a/src/Generated/Models/InternalCreateTranslationResponseVerboseJsonTask.cs b/src/Generated/Models/InternalCreateTranslationResponseVerboseJsonTask.cs index 089261285..22af3b6a7 100644 --- a/src/Generated/Models/InternalCreateTranslationResponseVerboseJsonTask.cs +++ b/src/Generated/Models/InternalCreateTranslationResponseVerboseJsonTask.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Audio { internal readonly partial struct InternalCreateTranslationResponseVerboseJsonTask : IEquatable { private readonly string _value; + private const string TranslateValue = "translate"; public InternalCreateTranslationResponseVerboseJsonTask(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TranslateValue = "translate"; + _value = value; + } public static InternalCreateTranslationResponseVerboseJsonTask Translate { get; } = new InternalCreateTranslationResponseVerboseJsonTask(TranslateValue); + public static bool operator ==(InternalCreateTranslationResponseVerboseJsonTask left, InternalCreateTranslationResponseVerboseJsonTask right) => left.Equals(right); + public static bool operator !=(InternalCreateTranslationResponseVerboseJsonTask left, InternalCreateTranslationResponseVerboseJsonTask right) => !left.Equals(right); + public static implicit operator InternalCreateTranslationResponseVerboseJsonTask(string value) => new InternalCreateTranslationResponseVerboseJsonTask(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateTranslationResponseVerboseJsonTask other && Equals(other); + public bool Equals(InternalCreateTranslationResponseVerboseJsonTask other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs b/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs index e2ed769ba..121cd3ce8 100644 --- a/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateUploadRequest.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { internal partial class InternalCreateUploadRequest : IJsonModel { + internal InternalCreateUploadRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateUploadRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filename") != true) + if (_additionalBinaryDataProperties?.ContainsKey("filename") != true) { writer.WritePropertyName("filename"u8); writer.WriteStringValue(Filename); } - if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + if (_additionalBinaryDataProperties?.ContainsKey("purpose") != true) { writer.WritePropertyName("purpose"u8); writer.WriteStringValue(Purpose.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + if (_additionalBinaryDataProperties?.ContainsKey("bytes") != true) { writer.WritePropertyName("bytes"u8); writer.WriteNumberValue(Bytes); } - if (SerializedAdditionalRawData?.ContainsKey("mime_type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("mime_type") != true) { writer.WritePropertyName("mime_type"u8); writer.WriteStringValue(MimeType); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,25 +70,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - InternalCreateUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateUploadRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateUploadRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateUploadRequest(document.RootElement, options); } - internal static InternalCreateUploadRequest DeserializeInternalCreateUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateUploadRequest DeserializeInternalCreateUploadRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -87,44 +95,42 @@ internal static InternalCreateUploadRequest DeserializeInternalCreateUploadReque InternalCreateUploadRequestPurpose purpose = default; int bytes = default; string mimeType = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("filename"u8)) + if (prop.NameEquals("filename"u8)) { - filename = property.Value.GetString(); + filename = prop.Value.GetString(); continue; } - if (property.NameEquals("purpose"u8)) + if (prop.NameEquals("purpose"u8)) { - purpose = new InternalCreateUploadRequestPurpose(property.Value.GetString()); + purpose = new InternalCreateUploadRequestPurpose(prop.Value.GetString()); continue; } - if (property.NameEquals("bytes"u8)) + if (prop.NameEquals("bytes"u8)) { - bytes = property.Value.GetInt32(); + bytes = prop.Value.GetInt32(); continue; } - if (property.NameEquals("mime_type"u8)) + if (prop.NameEquals("mime_type"u8)) { - mimeType = property.Value.GetString(); + mimeType = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateUploadRequest(filename, purpose, bytes, mimeType, serializedAdditionalRawData); + return new InternalCreateUploadRequest(filename, purpose, bytes, mimeType, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalCreateUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateUploadRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateUploadRequest(document.RootElement, options); } default: @@ -152,15 +159,20 @@ InternalCreateUploadRequest IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateUploadRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateUploadRequest internalCreateUploadRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateUploadRequest(document.RootElement); + if (internalCreateUploadRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateUploadRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateUploadRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateUploadRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateUploadRequest.cs b/src/Generated/Models/InternalCreateUploadRequest.cs index f580307a6..0fc06c1e2 100644 --- a/src/Generated/Models/InternalCreateUploadRequest.cs +++ b/src/Generated/Models/InternalCreateUploadRequest.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Files { internal partial class InternalCreateUploadRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateUploadRequest(string filename, InternalCreateUploadRequestPurpose purpose, int bytes, string mimeType) { Argument.AssertNotNull(filename, nameof(filename)); @@ -21,22 +23,27 @@ public InternalCreateUploadRequest(string filename, InternalCreateUploadRequestP MimeType = mimeType; } - internal InternalCreateUploadRequest(string filename, InternalCreateUploadRequestPurpose purpose, int bytes, string mimeType, IDictionary serializedAdditionalRawData) + internal InternalCreateUploadRequest(string filename, InternalCreateUploadRequestPurpose purpose, int bytes, string mimeType, IDictionary additionalBinaryDataProperties) { Filename = filename; Purpose = purpose; Bytes = bytes; MimeType = mimeType; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateUploadRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Filename { get; } + public InternalCreateUploadRequestPurpose Purpose { get; } + public int Bytes { get; } + public string MimeType { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateUploadRequestPurpose.cs b/src/Generated/Models/InternalCreateUploadRequestPurpose.cs index 6b76958f0..f50d74b22 100644 --- a/src/Generated/Models/InternalCreateUploadRequestPurpose.cs +++ b/src/Generated/Models/InternalCreateUploadRequestPurpose.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalCreateUploadRequestPurpose : IEquatable { private readonly string _value; - - public InternalCreateUploadRequestPurpose(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string AssistantsValue = "assistants"; private const string BatchValue = "batch"; private const string FineTuneValue = "fine-tune"; private const string VisionValue = "vision"; + public InternalCreateUploadRequestPurpose(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalCreateUploadRequestPurpose Assistants { get; } = new InternalCreateUploadRequestPurpose(AssistantsValue); + public static InternalCreateUploadRequestPurpose Batch { get; } = new InternalCreateUploadRequestPurpose(BatchValue); + public static InternalCreateUploadRequestPurpose FineTune { get; } = new InternalCreateUploadRequestPurpose(FineTuneValue); + public static InternalCreateUploadRequestPurpose Vision { get; } = new InternalCreateUploadRequestPurpose(VisionValue); + public static bool operator ==(InternalCreateUploadRequestPurpose left, InternalCreateUploadRequestPurpose right) => left.Equals(right); + public static bool operator !=(InternalCreateUploadRequestPurpose left, InternalCreateUploadRequestPurpose right) => !left.Equals(right); + public static implicit operator InternalCreateUploadRequestPurpose(string value) => new InternalCreateUploadRequestPurpose(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalCreateUploadRequestPurpose other && Equals(other); + public bool Equals(InternalCreateUploadRequestPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.Serialization.cs b/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.Serialization.cs index 90585d41f..792fe9f39 100644 --- a/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.Serialization.cs @@ -7,35 +7,50 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalCreateVectorStoreFileBatchRequest : IJsonModel { + internal InternalCreateVectorStoreFileBatchRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateVectorStoreFileBatchRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) + if (Optional.IsDefined(ChunkingStrategy) && _additionalBinaryDataProperties?.ContainsKey("chunking_strategy") != true) { writer.WritePropertyName("chunking_strategy"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(ChunkingStrategy); + writer.WriteRawValue(ChunkingStrategy); #else using (JsonDocument document = JsonDocument.Parse(ChunkingStrategy)) { @@ -43,9 +58,9 @@ void IJsonModel.Write(Utf8JsonWriter } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +68,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,68 +77,71 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalCreateVectorStoreFileBatchRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateVectorStoreFileBatchRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateVectorStoreFileBatchRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateVectorStoreFileBatchRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateVectorStoreFileBatchRequest(document.RootElement, options); } - internal static InternalCreateVectorStoreFileBatchRequest DeserializeInternalCreateVectorStoreFileBatchRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateVectorStoreFileBatchRequest DeserializeInternalCreateVectorStoreFileBatchRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; BinaryData chunkingStrategy = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } - if (property.NameEquals("chunking_strategy"u8)) + if (prop.NameEquals("chunking_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - chunkingStrategy = BinaryData.FromString(property.Value.GetRawText()); + chunkingStrategy = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateVectorStoreFileBatchRequest(fileIds, chunkingStrategy, serializedAdditionalRawData); + return new InternalCreateVectorStoreFileBatchRequest(fileIds, chunkingStrategy, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -133,15 +151,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalCreateVectorStoreFileBatchRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateVectorStoreFileBatchRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateVectorStoreFileBatchRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateVectorStoreFileBatchRequest(document.RootElement, options); } default: @@ -151,15 +170,20 @@ InternalCreateVectorStoreFileBatchRequest IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateVectorStoreFileBatchRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateVectorStoreFileBatchRequest internalCreateVectorStoreFileBatchRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateVectorStoreFileBatchRequest(document.RootElement); + if (internalCreateVectorStoreFileBatchRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateVectorStoreFileBatchRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateVectorStoreFileBatchRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateVectorStoreFileBatchRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.cs b/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.cs index 3064e3505..05db1f8a6 100644 --- a/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.cs +++ b/src/Generated/Models/InternalCreateVectorStoreFileBatchRequest.cs @@ -5,12 +5,14 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalCreateVectorStoreFileBatchRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateVectorStoreFileBatchRequest(IEnumerable fileIds) { Argument.AssertNotNull(fileIds, nameof(fileIds)); @@ -18,18 +20,21 @@ public InternalCreateVectorStoreFileBatchRequest(IEnumerable fileIds) FileIds = fileIds.ToList(); } - internal InternalCreateVectorStoreFileBatchRequest(IList fileIds, BinaryData chunkingStrategy, IDictionary serializedAdditionalRawData) + internal InternalCreateVectorStoreFileBatchRequest(IList fileIds, BinaryData chunkingStrategy, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; ChunkingStrategy = chunkingStrategy; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalCreateVectorStoreFileBatchRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + public BinaryData ChunkingStrategy { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalCreateVectorStoreFileRequest.Serialization.cs b/src/Generated/Models/InternalCreateVectorStoreFileRequest.Serialization.cs index 4e124f18f..ea7862847 100644 --- a/src/Generated/Models/InternalCreateVectorStoreFileRequest.Serialization.cs +++ b/src/Generated/Models/InternalCreateVectorStoreFileRequest.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalCreateVectorStoreFileRequest : IJsonModel { + internal InternalCreateVectorStoreFileRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalCreateVectorStoreFileRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) + if (Optional.IsDefined(ChunkingStrategy) && _additionalBinaryDataProperties?.ContainsKey("chunking_strategy") != true) { writer.WritePropertyName("chunking_strategy"u8); writer.WriteObjectValue(ChunkingStrategy, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter write } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,63 +60,59 @@ void IJsonModel.Write(Utf8JsonWriter write #endif } } - writer.WriteEndObject(); } - InternalCreateVectorStoreFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalCreateVectorStoreFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalCreateVectorStoreFileRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalCreateVectorStoreFileRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalCreateVectorStoreFileRequest(document.RootElement, options); } - internal static InternalCreateVectorStoreFileRequest DeserializeInternalCreateVectorStoreFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalCreateVectorStoreFileRequest DeserializeInternalCreateVectorStoreFileRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; FileChunkingStrategy chunkingStrategy = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("chunking_strategy"u8)) + if (prop.NameEquals("chunking_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(property.Value, options); + chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalCreateVectorStoreFileRequest(fileId, chunkingStrategy, serializedAdditionalRawData); + return new InternalCreateVectorStoreFileRequest(fileId, chunkingStrategy, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -116,15 +122,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - InternalCreateVectorStoreFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalCreateVectorStoreFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalCreateVectorStoreFileRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalCreateVectorStoreFileRequest(document.RootElement, options); } default: @@ -134,15 +141,20 @@ InternalCreateVectorStoreFileRequest IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalCreateVectorStoreFileRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalCreateVectorStoreFileRequest internalCreateVectorStoreFileRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalCreateVectorStoreFileRequest(document.RootElement); + if (internalCreateVectorStoreFileRequest == null) + { + return null; + } + return BinaryContent.Create(internalCreateVectorStoreFileRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalCreateVectorStoreFileRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalCreateVectorStoreFileRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalCreateVectorStoreFileRequest.cs b/src/Generated/Models/InternalCreateVectorStoreFileRequest.cs index 4224f5fca..22b73113b 100644 --- a/src/Generated/Models/InternalCreateVectorStoreFileRequest.cs +++ b/src/Generated/Models/InternalCreateVectorStoreFileRequest.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalCreateVectorStoreFileRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalCreateVectorStoreFileRequest(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -17,17 +19,19 @@ public InternalCreateVectorStoreFileRequest(string fileId) FileId = fileId; } - internal InternalCreateVectorStoreFileRequest(string fileId, FileChunkingStrategy chunkingStrategy, IDictionary serializedAdditionalRawData) + internal InternalCreateVectorStoreFileRequest(string fileId, FileChunkingStrategy chunkingStrategy, IDictionary additionalBinaryDataProperties) { FileId = fileId; ChunkingStrategy = chunkingStrategy; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalCreateVectorStoreFileRequest() + public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; } } } diff --git a/src/Generated/Models/InternalDeleteAssistantResponseObject.cs b/src/Generated/Models/InternalDeleteAssistantResponseObject.cs index 1ee139041..6225c734b 100644 --- a/src/Generated/Models/InternalDeleteAssistantResponseObject.cs +++ b/src/Generated/Models/InternalDeleteAssistantResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalDeleteAssistantResponseObject : IEquatable { private readonly string _value; + private const string AssistantDeletedValue = "assistant.deleted"; public InternalDeleteAssistantResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AssistantDeletedValue = "assistant.deleted"; + _value = value; + } public static InternalDeleteAssistantResponseObject AssistantDeleted { get; } = new InternalDeleteAssistantResponseObject(AssistantDeletedValue); + public static bool operator ==(InternalDeleteAssistantResponseObject left, InternalDeleteAssistantResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteAssistantResponseObject left, InternalDeleteAssistantResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteAssistantResponseObject(string value) => new InternalDeleteAssistantResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteAssistantResponseObject other && Equals(other); + public bool Equals(InternalDeleteAssistantResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteFileResponseObject.cs b/src/Generated/Models/InternalDeleteFileResponseObject.cs index f6fbfc918..488c1146e 100644 --- a/src/Generated/Models/InternalDeleteFileResponseObject.cs +++ b/src/Generated/Models/InternalDeleteFileResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalDeleteFileResponseObject : IEquatable { private readonly string _value; + private const string FileValue = "file"; public InternalDeleteFileResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FileValue = "file"; + _value = value; + } public static InternalDeleteFileResponseObject File { get; } = new InternalDeleteFileResponseObject(FileValue); + public static bool operator ==(InternalDeleteFileResponseObject left, InternalDeleteFileResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteFileResponseObject left, InternalDeleteFileResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteFileResponseObject(string value) => new InternalDeleteFileResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteFileResponseObject other && Equals(other); + public bool Equals(InternalDeleteFileResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteMessageResponseObject.cs b/src/Generated/Models/InternalDeleteMessageResponseObject.cs index 772ffbcb3..5bac8c4fa 100644 --- a/src/Generated/Models/InternalDeleteMessageResponseObject.cs +++ b/src/Generated/Models/InternalDeleteMessageResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalDeleteMessageResponseObject : IEquatable { private readonly string _value; + private const string ThreadMessageDeletedValue = "thread.message.deleted"; public InternalDeleteMessageResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadMessageDeletedValue = "thread.message.deleted"; + _value = value; + } public static InternalDeleteMessageResponseObject ThreadMessageDeleted { get; } = new InternalDeleteMessageResponseObject(ThreadMessageDeletedValue); + public static bool operator ==(InternalDeleteMessageResponseObject left, InternalDeleteMessageResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteMessageResponseObject left, InternalDeleteMessageResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteMessageResponseObject(string value) => new InternalDeleteMessageResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteMessageResponseObject other && Equals(other); + public bool Equals(InternalDeleteMessageResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteModelResponseObject.cs b/src/Generated/Models/InternalDeleteModelResponseObject.cs index 967d11d7a..b2bf4456c 100644 --- a/src/Generated/Models/InternalDeleteModelResponseObject.cs +++ b/src/Generated/Models/InternalDeleteModelResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Models { internal readonly partial struct InternalDeleteModelResponseObject : IEquatable { private readonly string _value; + private const string ModelValue = "model"; public InternalDeleteModelResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ModelValue = "model"; + _value = value; + } public static InternalDeleteModelResponseObject Model { get; } = new InternalDeleteModelResponseObject(ModelValue); + public static bool operator ==(InternalDeleteModelResponseObject left, InternalDeleteModelResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteModelResponseObject left, InternalDeleteModelResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteModelResponseObject(string value) => new InternalDeleteModelResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteModelResponseObject other && Equals(other); + public bool Equals(InternalDeleteModelResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteThreadResponseObject.cs b/src/Generated/Models/InternalDeleteThreadResponseObject.cs index bc843faac..37b6f7144 100644 --- a/src/Generated/Models/InternalDeleteThreadResponseObject.cs +++ b/src/Generated/Models/InternalDeleteThreadResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalDeleteThreadResponseObject : IEquatable { private readonly string _value; + private const string ThreadDeletedValue = "thread.deleted"; public InternalDeleteThreadResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadDeletedValue = "thread.deleted"; + _value = value; + } public static InternalDeleteThreadResponseObject ThreadDeleted { get; } = new InternalDeleteThreadResponseObject(ThreadDeletedValue); + public static bool operator ==(InternalDeleteThreadResponseObject left, InternalDeleteThreadResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteThreadResponseObject left, InternalDeleteThreadResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteThreadResponseObject(string value) => new InternalDeleteThreadResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteThreadResponseObject other && Equals(other); + public bool Equals(InternalDeleteThreadResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteVectorStoreFileResponseObject.cs b/src/Generated/Models/InternalDeleteVectorStoreFileResponseObject.cs index 6716460af..ec1f0afed 100644 --- a/src/Generated/Models/InternalDeleteVectorStoreFileResponseObject.cs +++ b/src/Generated/Models/InternalDeleteVectorStoreFileResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalDeleteVectorStoreFileResponseObject : IEquatable { private readonly string _value; + private const string VectorStoreFileDeletedValue = "vector_store.file.deleted"; public InternalDeleteVectorStoreFileResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VectorStoreFileDeletedValue = "vector_store.file.deleted"; + _value = value; + } public static InternalDeleteVectorStoreFileResponseObject VectorStoreFileDeleted { get; } = new InternalDeleteVectorStoreFileResponseObject(VectorStoreFileDeletedValue); + public static bool operator ==(InternalDeleteVectorStoreFileResponseObject left, InternalDeleteVectorStoreFileResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteVectorStoreFileResponseObject left, InternalDeleteVectorStoreFileResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteVectorStoreFileResponseObject(string value) => new InternalDeleteVectorStoreFileResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteVectorStoreFileResponseObject other && Equals(other); + public bool Equals(InternalDeleteVectorStoreFileResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalDeleteVectorStoreResponseObject.cs b/src/Generated/Models/InternalDeleteVectorStoreResponseObject.cs index c13ec4b2f..933ba71f7 100644 --- a/src/Generated/Models/InternalDeleteVectorStoreResponseObject.cs +++ b/src/Generated/Models/InternalDeleteVectorStoreResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalDeleteVectorStoreResponseObject : IEquatable { private readonly string _value; + private const string VectorStoreDeletedValue = "vector_store.deleted"; public InternalDeleteVectorStoreResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VectorStoreDeletedValue = "vector_store.deleted"; + _value = value; + } public static InternalDeleteVectorStoreResponseObject VectorStoreDeleted { get; } = new InternalDeleteVectorStoreResponseObject(VectorStoreDeletedValue); + public static bool operator ==(InternalDeleteVectorStoreResponseObject left, InternalDeleteVectorStoreResponseObject right) => left.Equals(right); + public static bool operator !=(InternalDeleteVectorStoreResponseObject left, InternalDeleteVectorStoreResponseObject right) => !left.Equals(right); + public static implicit operator InternalDeleteVectorStoreResponseObject(string value) => new InternalDeleteVectorStoreResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalDeleteVectorStoreResponseObject other && Equals(other); + public bool Equals(InternalDeleteVectorStoreResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalEmbeddingObject.cs b/src/Generated/Models/InternalEmbeddingObject.cs index 5a0c0e4d3..493e5ca4e 100644 --- a/src/Generated/Models/InternalEmbeddingObject.cs +++ b/src/Generated/Models/InternalEmbeddingObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Embeddings { internal readonly partial struct InternalEmbeddingObject : IEquatable { private readonly string _value; + private const string EmbeddingValue = "embedding"; public InternalEmbeddingObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string EmbeddingValue = "embedding"; + _value = value; + } public static InternalEmbeddingObject Embedding { get; } = new InternalEmbeddingObject(EmbeddingValue); + public static bool operator ==(InternalEmbeddingObject left, InternalEmbeddingObject right) => left.Equals(right); + public static bool operator !=(InternalEmbeddingObject left, InternalEmbeddingObject right) => !left.Equals(right); + public static implicit operator InternalEmbeddingObject(string value) => new InternalEmbeddingObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalEmbeddingObject other && Equals(other); + public bool Equals(InternalEmbeddingObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalFileChunkingStrategyRequestParam.Serialization.cs b/src/Generated/Models/InternalFileChunkingStrategyRequestParam.Serialization.cs index 4a61d2d17..a79752d35 100644 --- a/src/Generated/Models/InternalFileChunkingStrategyRequestParam.Serialization.cs +++ b/src/Generated/Models/InternalFileChunkingStrategyRequestParam.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { [PersistableModelProxy(typeof(InternalUnknownFileChunkingStrategyRequestParamProxy))] - internal partial class InternalFileChunkingStrategyRequestParam : IJsonModel + internal abstract partial class InternalFileChunkingStrategyRequestParam : IJsonModel { + internal InternalFileChunkingStrategyRequestParam() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFileChunkingStrategyRequestParam)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter w } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter w #endif } } - writer.WriteEndObject(); } - InternalFileChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFileChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFileChunkingStrategyRequestParam JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFileChunkingStrategyRequestParam)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement, options); } - internal static InternalFileChunkingStrategyRequestParam DeserializeInternalFileChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFileChunkingStrategyRequestParam DeserializeInternalFileChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "auto": return InternalAutoChunkingStrategyRequestParam.DeserializeInternalAutoChunkingStrategyRequestParam(element, options); - case "static": return InternalStaticChunkingStrategyRequestParam.DeserializeInternalStaticChunkingStrategyRequestParam(element, options); + case "auto": + return InternalAutoChunkingStrategyRequestParam.DeserializeInternalAutoChunkingStrategyRequestParam(element, options); + case "static": + return InternalStaticChunkingStrategyRequestParam.DeserializeInternalStaticChunkingStrategyRequestParam(element, options); } } return InternalUnknownFileChunkingStrategyRequestParamProxy.DeserializeInternalUnknownFileChunkingStrategyRequestParamProxy(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalFileChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFileChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFileChunkingStrategyRequestParam 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement, options); } default: @@ -110,15 +122,20 @@ InternalFileChunkingStrategyRequestParam IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFileChunkingStrategyRequestParam FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFileChunkingStrategyRequestParam internalFileChunkingStrategyRequestParam) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement); + if (internalFileChunkingStrategyRequestParam == null) + { + return null; + } + return BinaryContent.Create(internalFileChunkingStrategyRequestParam, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFileChunkingStrategyRequestParam(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFileChunkingStrategyRequestParam.cs b/src/Generated/Models/InternalFileChunkingStrategyRequestParam.cs index 275a076ed..1dc6d0ab5 100644 --- a/src/Generated/Models/InternalFileChunkingStrategyRequestParam.cs +++ b/src/Generated/Models/InternalFileChunkingStrategyRequestParam.cs @@ -9,17 +9,25 @@ namespace OpenAI.VectorStores { internal abstract partial class InternalFileChunkingStrategyRequestParam { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalFileChunkingStrategyRequestParam() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalFileChunkingStrategyRequestParam(string @type) { + Type = @type; } - internal InternalFileChunkingStrategyRequestParam(string type, IDictionary serializedAdditionalRawData) + internal InternalFileChunkingStrategyRequestParam(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFileUploadOptions.Serialization.cs b/src/Generated/Models/InternalFileUploadOptions.Serialization.cs index 8a86ad75b..b990c6541 100644 --- a/src/Generated/Models/InternalFileUploadOptions.Serialization.cs +++ b/src/Generated/Models/InternalFileUploadOptions.Serialization.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.IO; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { @@ -15,18 +16,23 @@ internal partial class InternalFileUploadOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFileUploadOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file") != true) { writer.WritePropertyName("file"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(global::System.BinaryData.FromStream(File)); + writer.WriteRawValue(global::System.BinaryData.FromStream(File)); #else using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(File))) { @@ -34,14 +40,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } #endif } - if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + if (_additionalBinaryDataProperties?.ContainsKey("purpose") != true) { writer.WritePropertyName("purpose"u8); writer.WriteStringValue(Purpose.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -49,7 +55,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -58,102 +64,74 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - InternalFileUploadOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFileUploadOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFileUploadOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFileUploadOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFileUploadOptions(document.RootElement, options); } - internal static InternalFileUploadOptions DeserializeInternalFileUploadOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFileUploadOptions DeserializeInternalFileUploadOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - Stream file = default; + Stream @file = default; FileUploadPurpose purpose = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file"u8)) + if (prop.NameEquals("file"u8)) { - file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + @file = BinaryData.FromString(prop.Value.GetRawText()).ToStream(); continue; } - if (property.NameEquals("purpose"u8)) + if (prop.NameEquals("purpose"u8)) { - purpose = new FileUploadPurpose(property.Value.GetString()); + purpose = new FileUploadPurpose(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalFileUploadOptions(file, purpose, serializedAdditionalRawData); - } - - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataBinaryContent content = ToMultipartBinaryBody(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } + return new InternalFileUploadOptions(@file, purpose, additionalBinaryDataProperties); } - internal virtual MultipartFormDataBinaryContent ToMultipartBinaryBody() - { - MultipartFormDataBinaryContent content = new MultipartFormDataBinaryContent(); - content.Add(File, "file", "file", "application/octet-stream"); - content.Add(Purpose.ToString(), "purpose"); - return content; - } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(InternalFileUploadOptions)} does not support writing '{options.Format}' format."); } } - InternalFileUploadOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFileUploadOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFileUploadOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFileUploadOptions(document.RootElement, options); } default: @@ -161,17 +139,22 @@ InternalFileUploadOptions IPersistableModel.Create(Bi } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFileUploadOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFileUploadOptions internalFileUploadOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFileUploadOptions(document.RootElement); + if (internalFileUploadOptions == null) + { + return null; + } + return BinaryContent.Create(internalFileUploadOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFileUploadOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFileUploadOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFileUploadOptions.cs b/src/Generated/Models/InternalFileUploadOptions.cs index 7873ae62e..e53004253 100644 --- a/src/Generated/Models/InternalFileUploadOptions.cs +++ b/src/Generated/Models/InternalFileUploadOptions.cs @@ -10,13 +10,19 @@ namespace OpenAI.Files { internal partial class InternalFileUploadOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal InternalFileUploadOptions(Stream file, FileUploadPurpose purpose, IDictionary serializedAdditionalRawData) + internal InternalFileUploadOptions(Stream @file, FileUploadPurpose purpose, IDictionary additionalBinaryDataProperties) { - File = file; + File = @file; Purpose = purpose; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs b/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs index 23c976dc2..98cf117e0 100644 --- a/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs +++ b/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Chat; namespace OpenAI.FineTuning @@ -15,186 +16,119 @@ internal partial class InternalFineTuneChatCompletionRequestAssistantMessage : I { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuneChatCompletionRequestAssistantMessage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && Optional.IsDefined(Refusal)) - { - if (Refusal != null) - { - writer.WritePropertyName("refusal"u8); - writer.WriteStringValue(Refusal); - } - else - { - writer.WriteNull("refusal"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(ParticipantName)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(ParticipantName); - } - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true && Optional.IsCollectionDefined(ToolCalls)) - { - writer.WritePropertyName("tool_calls"u8); - writer.WriteStartArray(); - foreach (var item in ToolCalls) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("function_call") != true && Optional.IsDefined(FunctionCall)) - { - if (FunctionCall != null) - { - writer.WritePropertyName("function_call"u8); - writer.WriteObjectValue(FunctionCall, options); - } - else - { - writer.WriteNull("function_call"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToSerialString()); - } - // CUSTOM: Check inner collection is defined. - if (SerializedAdditionalRawData?.ContainsKey("content") != true && true && Optional.IsDefined(Content) && Content.IsInnerCollectionDefined()) - { - writer.WritePropertyName("content"u8); - SerializeContentValue(writer, options); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalFineTuneChatCompletionRequestAssistantMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuneChatCompletionRequestAssistantMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalFineTuneChatCompletionRequestAssistantMessage)JsonModelCreateCore(ref reader, options); + + protected override ChatMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuneChatCompletionRequestAssistantMessage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(document.RootElement, options); } - internal static InternalFineTuneChatCompletionRequestAssistantMessage DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFineTuneChatCompletionRequestAssistantMessage DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + Chat.ChatMessageRole role = default; + ChatMessageContent content = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string refusal = default; - string name = default; + string participantName = default; IList toolCalls = default; ChatFunctionCall functionCall = default; - ChatMessageRole role = default; - ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + 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 = property.Value.GetString(); + refusal = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + participantName = prop.Value.GetString(); continue; } - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatToolCall.DeserializeChatToolCall(item, options)); } toolCalls = array; continue; } - if (property.NameEquals("function_call"u8)) + if (prop.NameEquals("function_call"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { functionCall = null; continue; } - functionCall = ChatFunctionCall.DeserializeChatFunctionCall(property.Value, options); - continue; - } - if (property.NameEquals("role"u8)) - { - role = property.Value.GetString().ToChatMessageRole(); - continue; - } - if (property.NameEquals("content"u8)) - { - DeserializeContentValue(property, ref content); + functionCall = ChatFunctionCall.DeserializeChatFunctionCall(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. return new InternalFineTuneChatCompletionRequestAssistantMessage( role, content ?? new ChatMessageContent(), - serializedAdditionalRawData, + additionalBinaryDataProperties, refusal, - name, + participantName, toolCalls ?? new ChangeTrackingList(), functionCall); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -204,15 +138,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuneChatCompletionRequestAssistantMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalFineTuneChatCompletionRequestAssistantMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(document.RootElement, options); } default: @@ -222,15 +157,20 @@ InternalFineTuneChatCompletionRequestAssistantMessage IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalFineTuneChatCompletionRequestAssistantMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFineTuneChatCompletionRequestAssistantMessage internalFineTuneChatCompletionRequestAssistantMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(document.RootElement); + if (internalFineTuneChatCompletionRequestAssistantMessage == null) + { + return null; + } + return BinaryContent.Create(internalFineTuneChatCompletionRequestAssistantMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalFineTuneChatCompletionRequestAssistantMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFineTuneChatCompletionRequestAssistantMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs b/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs index f7041aa39..868aa7ef7 100644 --- a/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs +++ b/src/Generated/Models/InternalFineTuneChatCompletionRequestAssistantMessage.cs @@ -14,7 +14,7 @@ public InternalFineTuneChatCompletionRequestAssistantMessage() { } - internal InternalFineTuneChatCompletionRequestAssistantMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, serializedAdditionalRawData, refusal, participantName, toolCalls, functionCall) + internal InternalFineTuneChatCompletionRequestAssistantMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string refusal, string participantName, IList toolCalls, ChatFunctionCall functionCall) : base(role, content, additionalBinaryDataProperties, refusal, participantName, toolCalls, functionCall) { } } diff --git a/src/Generated/Models/InternalFineTuningIntegration.Serialization.cs b/src/Generated/Models/InternalFineTuningIntegration.Serialization.cs index c6cdd8c10..131661504 100644 --- a/src/Generated/Models/InternalFineTuningIntegration.Serialization.cs +++ b/src/Generated/Models/InternalFineTuningIntegration.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { [PersistableModelProxy(typeof(UnknownFineTuningIntegration))] - internal partial class InternalFineTuningIntegration : IJsonModel + internal abstract partial class InternalFineTuningIntegration : IJsonModel { + internal InternalFineTuningIntegration() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuningIntegration)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,43 +55,43 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode #endif } } - writer.WriteEndObject(); } - InternalFineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuningIntegration)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuningIntegration(document.RootElement, options); } - internal static InternalFineTuningIntegration DeserializeInternalFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFineTuningIntegration DeserializeInternalFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "wandb": return InternalFineTuningIntegrationWandb.DeserializeInternalFineTuningIntegrationWandb(element, options); + case "wandb": + return InternalFineTuningIntegrationWandb.DeserializeInternalFineTuningIntegrationWandb(element, options); } } return UnknownFineTuningIntegration.DeserializeUnknownFineTuningIntegration(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -91,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - InternalFineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuningIntegration(document.RootElement, options); } default: @@ -109,15 +120,20 @@ InternalFineTuningIntegration IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFineTuningIntegration FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFineTuningIntegration internalFineTuningIntegration) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFineTuningIntegration(document.RootElement); + if (internalFineTuningIntegration == null) + { + return null; + } + return BinaryContent.Create(internalFineTuningIntegration, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFineTuningIntegration(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFineTuningIntegration(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFineTuningIntegration.cs b/src/Generated/Models/InternalFineTuningIntegration.cs index 4ee21aa07..5da15f4af 100644 --- a/src/Generated/Models/InternalFineTuningIntegration.cs +++ b/src/Generated/Models/InternalFineTuningIntegration.cs @@ -9,17 +9,25 @@ namespace OpenAI.FineTuning { internal abstract partial class InternalFineTuningIntegration { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalFineTuningIntegration() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalFineTuningIntegration(string @type) { + Type = @type; } - internal InternalFineTuningIntegration(string type, IDictionary serializedAdditionalRawData) + internal InternalFineTuningIntegration(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFineTuningIntegrationWandb.Serialization.cs b/src/Generated/Models/InternalFineTuningIntegrationWandb.Serialization.cs index a8ff8e640..68744bf46 100644 --- a/src/Generated/Models/InternalFineTuningIntegrationWandb.Serialization.cs +++ b/src/Generated/Models/InternalFineTuningIntegrationWandb.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalFineTuningIntegrationWandb : IJsonModel { + internal InternalFineTuningIntegrationWandb() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuningIntegrationWandb)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("wandb") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("wandb") != true) { writer.WritePropertyName("wandb"u8); writer.WriteObjectValue(Wandb, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalFineTuningIntegrationWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuningIntegrationWandb IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalFineTuningIntegrationWandb)JsonModelCreateCore(ref reader, options); + + protected override InternalFineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuningIntegrationWandb)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuningIntegrationWandb(document.RootElement, options); } - internal static InternalFineTuningIntegrationWandb DeserializeInternalFineTuningIntegrationWandb(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFineTuningIntegrationWandb DeserializeInternalFineTuningIntegrationWandb(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "wandb"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); FineTuningIntegrationWandbWandb wandb = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("wandb"u8)) + if (prop.NameEquals("type"u8)) { - wandb = FineTuningIntegrationWandbWandb.DeserializeFineTuningIntegrationWandbWandb(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("wandb"u8)) { - type = property.Value.GetString(); + wandb = FineTuningIntegrationWandbWandb.DeserializeFineTuningIntegrationWandbWandb(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalFineTuningIntegrationWandb(type, serializedAdditionalRawData, wandb); + return new InternalFineTuningIntegrationWandb(@type, additionalBinaryDataProperties, wandb); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - InternalFineTuningIntegrationWandb IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuningIntegrationWandb IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalFineTuningIntegrationWandb)PersistableModelCreateCore(data, options); + protected override InternalFineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuningIntegrationWandb(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalFineTuningIntegrationWandb IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalFineTuningIntegrationWandb FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFineTuningIntegrationWandb internalFineTuningIntegrationWandb) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFineTuningIntegrationWandb(document.RootElement); + if (internalFineTuningIntegrationWandb == null) + { + return null; + } + return BinaryContent.Create(internalFineTuningIntegrationWandb, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalFineTuningIntegrationWandb(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFineTuningIntegrationWandb(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFineTuningIntegrationWandb.cs b/src/Generated/Models/InternalFineTuningIntegrationWandb.cs index 02a6deab0..1b1102d94 100644 --- a/src/Generated/Models/InternalFineTuningIntegrationWandb.cs +++ b/src/Generated/Models/InternalFineTuningIntegrationWandb.cs @@ -9,23 +9,16 @@ namespace OpenAI.FineTuning { internal partial class InternalFineTuningIntegrationWandb : InternalFineTuningIntegration { - internal InternalFineTuningIntegrationWandb(FineTuningIntegrationWandbWandb wandb) + internal InternalFineTuningIntegrationWandb(FineTuningIntegrationWandbWandb wandb) : base("wandb") { - Argument.AssertNotNull(wandb, nameof(wandb)); - - Type = "wandb"; Wandb = wandb; } - internal InternalFineTuningIntegrationWandb(string type, IDictionary serializedAdditionalRawData, FineTuningIntegrationWandbWandb wandb) : base(type, serializedAdditionalRawData) + internal InternalFineTuningIntegrationWandb(string @type, IDictionary additionalBinaryDataProperties, FineTuningIntegrationWandbWandb wandb) : base(@type, additionalBinaryDataProperties) { Wandb = wandb; } - internal InternalFineTuningIntegrationWandb() - { - } - public FineTuningIntegrationWandbWandb Wandb { get; } } } diff --git a/src/Generated/Models/InternalFineTuningJobCheckpoint.Serialization.cs b/src/Generated/Models/InternalFineTuningJobCheckpoint.Serialization.cs index d562b0cbd..ef1ab9143 100644 --- a/src/Generated/Models/InternalFineTuningJobCheckpoint.Serialization.cs +++ b/src/Generated/Models/InternalFineTuningJobCheckpoint.Serialization.cs @@ -7,58 +7,68 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalFineTuningJobCheckpoint : IJsonModel { + internal InternalFineTuningJobCheckpoint() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuningJobCheckpoint)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("fine_tuned_model_checkpoint") != true) + if (_additionalBinaryDataProperties?.ContainsKey("fine_tuned_model_checkpoint") != true) { writer.WritePropertyName("fine_tuned_model_checkpoint"u8); writer.WriteStringValue(FineTunedModelCheckpoint); } - if (SerializedAdditionalRawData?.ContainsKey("step_number") != true) + if (_additionalBinaryDataProperties?.ContainsKey("step_number") != true) { writer.WritePropertyName("step_number"u8); writer.WriteNumberValue(StepNumber); } - if (SerializedAdditionalRawData?.ContainsKey("metrics") != true) + if (_additionalBinaryDataProperties?.ContainsKey("metrics") != true) { writer.WritePropertyName("metrics"u8); writer.WriteObjectValue(Metrics, options); } - if (SerializedAdditionalRawData?.ContainsKey("fine_tuning_job_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("fine_tuning_job_id") != true) { writer.WritePropertyName("fine_tuning_job_id"u8); writer.WriteStringValue(FineTuningJobId); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -66,7 +76,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -75,25 +85,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalFineTuningJobCheckpoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuningJobCheckpoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFineTuningJobCheckpoint JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuningJobCheckpoint)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuningJobCheckpoint(document.RootElement, options); } - internal static InternalFineTuningJobCheckpoint DeserializeInternalFineTuningJobCheckpoint(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFineTuningJobCheckpoint DeserializeInternalFineTuningJobCheckpoint(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -105,52 +113,49 @@ internal static InternalFineTuningJobCheckpoint DeserializeInternalFineTuningJob InternalFineTuningJobCheckpointMetrics metrics = default; string fineTuningJobId = default; InternalFineTuningJobCheckpointObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("fine_tuned_model_checkpoint"u8)) + if (prop.NameEquals("fine_tuned_model_checkpoint"u8)) { - fineTunedModelCheckpoint = property.Value.GetString(); + fineTunedModelCheckpoint = prop.Value.GetString(); continue; } - if (property.NameEquals("step_number"u8)) + if (prop.NameEquals("step_number"u8)) { - stepNumber = property.Value.GetInt32(); + stepNumber = prop.Value.GetInt32(); continue; } - if (property.NameEquals("metrics"u8)) + if (prop.NameEquals("metrics"u8)) { - metrics = InternalFineTuningJobCheckpointMetrics.DeserializeInternalFineTuningJobCheckpointMetrics(property.Value, options); + metrics = InternalFineTuningJobCheckpointMetrics.DeserializeInternalFineTuningJobCheckpointMetrics(prop.Value, options); continue; } - if (property.NameEquals("fine_tuning_job_id"u8)) + if (prop.NameEquals("fine_tuning_job_id"u8)) { - fineTuningJobId = property.Value.GetString(); + fineTuningJobId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalFineTuningJobCheckpointObject(property.Value.GetString()); + @object = new InternalFineTuningJobCheckpointObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalFineTuningJobCheckpoint( id, createdAt, @@ -159,13 +164,14 @@ internal static InternalFineTuningJobCheckpoint DeserializeInternalFineTuningJob metrics, fineTuningJobId, @object, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +181,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalFineTuningJobCheckpoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuningJobCheckpoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFineTuningJobCheckpoint 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuningJobCheckpoint(document.RootElement, options); } default: @@ -193,15 +200,20 @@ InternalFineTuningJobCheckpoint IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFineTuningJobCheckpoint FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFineTuningJobCheckpoint internalFineTuningJobCheckpoint) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFineTuningJobCheckpoint(document.RootElement); + if (internalFineTuningJobCheckpoint == null) + { + return null; + } + return BinaryContent.Create(internalFineTuningJobCheckpoint, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFineTuningJobCheckpoint(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFineTuningJobCheckpoint(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFineTuningJobCheckpoint.cs b/src/Generated/Models/InternalFineTuningJobCheckpoint.cs index 463cfd4fb..77dab5018 100644 --- a/src/Generated/Models/InternalFineTuningJobCheckpoint.cs +++ b/src/Generated/Models/InternalFineTuningJobCheckpoint.cs @@ -9,14 +9,10 @@ namespace OpenAI.FineTuning { internal partial class InternalFineTuningJobCheckpoint { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalFineTuningJobCheckpoint(string id, DateTimeOffset createdAt, string fineTunedModelCheckpoint, int stepNumber, InternalFineTuningJobCheckpointMetrics metrics, string fineTuningJobId) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(fineTunedModelCheckpoint, nameof(fineTunedModelCheckpoint)); - Argument.AssertNotNull(metrics, nameof(metrics)); - Argument.AssertNotNull(fineTuningJobId, nameof(fineTuningJobId)); - Id = id; CreatedAt = createdAt; FineTunedModelCheckpoint = fineTunedModelCheckpoint; @@ -25,7 +21,7 @@ internal InternalFineTuningJobCheckpoint(string id, DateTimeOffset createdAt, st FineTuningJobId = fineTuningJobId; } - internal InternalFineTuningJobCheckpoint(string id, DateTimeOffset createdAt, string fineTunedModelCheckpoint, int stepNumber, InternalFineTuningJobCheckpointMetrics metrics, string fineTuningJobId, InternalFineTuningJobCheckpointObject @object, IDictionary serializedAdditionalRawData) + internal InternalFineTuningJobCheckpoint(string id, DateTimeOffset createdAt, string fineTunedModelCheckpoint, int stepNumber, InternalFineTuningJobCheckpointMetrics metrics, string fineTuningJobId, InternalFineTuningJobCheckpointObject @object, IDictionary additionalBinaryDataProperties) { Id = id; CreatedAt = createdAt; @@ -34,19 +30,27 @@ internal InternalFineTuningJobCheckpoint(string id, DateTimeOffset createdAt, st Metrics = metrics; FineTuningJobId = fineTuningJobId; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalFineTuningJobCheckpoint() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string FineTunedModelCheckpoint { get; } + public int StepNumber { get; } + public InternalFineTuningJobCheckpointMetrics Metrics { get; } + public string FineTuningJobId { get; } - public InternalFineTuningJobCheckpointObject Object { get; } = InternalFineTuningJobCheckpointObject.FineTuningJobCheckpoint; + + public InternalFineTuningJobCheckpointObject Object { get; } = "fine_tuning.job.checkpoint"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.Serialization.cs b/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.Serialization.cs index 3c411f901..52ee0448d 100644 --- a/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.Serialization.cs +++ b/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { @@ -14,51 +15,56 @@ internal partial class InternalFineTuningJobCheckpointMetrics : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuningJobCheckpointMetrics)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("step") != true && Optional.IsDefined(Step)) + if (Optional.IsDefined(Step) && _additionalBinaryDataProperties?.ContainsKey("step") != true) { writer.WritePropertyName("step"u8); writer.WriteNumberValue(Step.Value); } - if (SerializedAdditionalRawData?.ContainsKey("train_loss") != true && Optional.IsDefined(TrainLoss)) + if (Optional.IsDefined(TrainLoss) && _additionalBinaryDataProperties?.ContainsKey("train_loss") != true) { writer.WritePropertyName("train_loss"u8); writer.WriteNumberValue(TrainLoss.Value); } - if (SerializedAdditionalRawData?.ContainsKey("train_mean_token_accuracy") != true && Optional.IsDefined(TrainMeanTokenAccuracy)) + if (Optional.IsDefined(TrainMeanTokenAccuracy) && _additionalBinaryDataProperties?.ContainsKey("train_mean_token_accuracy") != true) { writer.WritePropertyName("train_mean_token_accuracy"u8); writer.WriteNumberValue(TrainMeanTokenAccuracy.Value); } - if (SerializedAdditionalRawData?.ContainsKey("valid_loss") != true && Optional.IsDefined(ValidLoss)) + if (Optional.IsDefined(ValidLoss) && _additionalBinaryDataProperties?.ContainsKey("valid_loss") != true) { writer.WritePropertyName("valid_loss"u8); writer.WriteNumberValue(ValidLoss.Value); } - if (SerializedAdditionalRawData?.ContainsKey("valid_mean_token_accuracy") != true && Optional.IsDefined(ValidMeanTokenAccuracy)) + if (Optional.IsDefined(ValidMeanTokenAccuracy) && _additionalBinaryDataProperties?.ContainsKey("valid_mean_token_accuracy") != true) { writer.WritePropertyName("valid_mean_token_accuracy"u8); writer.WriteNumberValue(ValidMeanTokenAccuracy.Value); } - if (SerializedAdditionalRawData?.ContainsKey("full_valid_loss") != true && Optional.IsDefined(FullValidLoss)) + if (Optional.IsDefined(FullValidLoss) && _additionalBinaryDataProperties?.ContainsKey("full_valid_loss") != true) { writer.WritePropertyName("full_valid_loss"u8); writer.WriteNumberValue(FullValidLoss.Value); } - if (SerializedAdditionalRawData?.ContainsKey("full_valid_mean_token_accuracy") != true && Optional.IsDefined(FullValidMeanTokenAccuracy)) + if (Optional.IsDefined(FullValidMeanTokenAccuracy) && _additionalBinaryDataProperties?.ContainsKey("full_valid_mean_token_accuracy") != true) { writer.WritePropertyName("full_valid_mean_token_accuracy"u8); writer.WriteNumberValue(FullValidMeanTokenAccuracy.Value); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -66,7 +72,7 @@ void IJsonModel.Write(Utf8JsonWriter wri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -75,25 +81,23 @@ void IJsonModel.Write(Utf8JsonWriter wri #endif } } - writer.WriteEndObject(); } - InternalFineTuningJobCheckpointMetrics IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuningJobCheckpointMetrics IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFineTuningJobCheckpointMetrics JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuningJobCheckpointMetrics)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuningJobCheckpointMetrics(document.RootElement, options); } - internal static InternalFineTuningJobCheckpointMetrics DeserializeInternalFineTuningJobCheckpointMetrics(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFineTuningJobCheckpointMetrics DeserializeInternalFineTuningJobCheckpointMetrics(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -105,80 +109,77 @@ internal static InternalFineTuningJobCheckpointMetrics DeserializeInternalFineTu float? validMeanTokenAccuracy = default; float? fullValidLoss = default; float? fullValidMeanTokenAccuracy = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("step"u8)) + if (prop.NameEquals("step"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - step = property.Value.GetSingle(); + step = prop.Value.GetSingle(); continue; } - if (property.NameEquals("train_loss"u8)) + if (prop.NameEquals("train_loss"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - trainLoss = property.Value.GetSingle(); + trainLoss = prop.Value.GetSingle(); continue; } - if (property.NameEquals("train_mean_token_accuracy"u8)) + if (prop.NameEquals("train_mean_token_accuracy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - trainMeanTokenAccuracy = property.Value.GetSingle(); + trainMeanTokenAccuracy = prop.Value.GetSingle(); continue; } - if (property.NameEquals("valid_loss"u8)) + if (prop.NameEquals("valid_loss"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - validLoss = property.Value.GetSingle(); + validLoss = prop.Value.GetSingle(); continue; } - if (property.NameEquals("valid_mean_token_accuracy"u8)) + if (prop.NameEquals("valid_mean_token_accuracy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - validMeanTokenAccuracy = property.Value.GetSingle(); + validMeanTokenAccuracy = prop.Value.GetSingle(); continue; } - if (property.NameEquals("full_valid_loss"u8)) + if (prop.NameEquals("full_valid_loss"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fullValidLoss = property.Value.GetSingle(); + fullValidLoss = prop.Value.GetSingle(); continue; } - if (property.NameEquals("full_valid_mean_token_accuracy"u8)) + if (prop.NameEquals("full_valid_mean_token_accuracy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fullValidMeanTokenAccuracy = property.Value.GetSingle(); + fullValidMeanTokenAccuracy = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalFineTuningJobCheckpointMetrics( step, trainLoss, @@ -187,13 +188,14 @@ internal static InternalFineTuningJobCheckpointMetrics DeserializeInternalFineTu validMeanTokenAccuracy, fullValidLoss, fullValidMeanTokenAccuracy, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -203,15 +205,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalFineTuningJobCheckpointMetrics IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuningJobCheckpointMetrics IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFineTuningJobCheckpointMetrics 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuningJobCheckpointMetrics(document.RootElement, options); } default: @@ -221,15 +224,20 @@ InternalFineTuningJobCheckpointMetrics IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFineTuningJobCheckpointMetrics FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFineTuningJobCheckpointMetrics internalFineTuningJobCheckpointMetrics) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFineTuningJobCheckpointMetrics(document.RootElement); + if (internalFineTuningJobCheckpointMetrics == null) + { + return null; + } + return BinaryContent.Create(internalFineTuningJobCheckpointMetrics, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFineTuningJobCheckpointMetrics(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFineTuningJobCheckpointMetrics(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.cs b/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.cs index 63c7256ec..a59f09b9e 100644 --- a/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.cs +++ b/src/Generated/Models/InternalFineTuningJobCheckpointMetrics.cs @@ -9,12 +9,13 @@ namespace OpenAI.FineTuning { internal partial class InternalFineTuningJobCheckpointMetrics { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalFineTuningJobCheckpointMetrics() { } - internal InternalFineTuningJobCheckpointMetrics(float? step, float? trainLoss, float? trainMeanTokenAccuracy, float? validLoss, float? validMeanTokenAccuracy, float? fullValidLoss, float? fullValidMeanTokenAccuracy, IDictionary serializedAdditionalRawData) + internal InternalFineTuningJobCheckpointMetrics(float? step, float? trainLoss, float? trainMeanTokenAccuracy, float? validLoss, float? validMeanTokenAccuracy, float? fullValidLoss, float? fullValidMeanTokenAccuracy, IDictionary additionalBinaryDataProperties) { Step = step; TrainLoss = trainLoss; @@ -23,15 +24,27 @@ internal InternalFineTuningJobCheckpointMetrics(float? step, float? trainLoss, f ValidMeanTokenAccuracy = validMeanTokenAccuracy; FullValidLoss = fullValidLoss; FullValidMeanTokenAccuracy = fullValidMeanTokenAccuracy; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public float? Step { get; } + public float? TrainLoss { get; } + public float? TrainMeanTokenAccuracy { get; } + public float? ValidLoss { get; } + public float? ValidMeanTokenAccuracy { get; } + public float? FullValidLoss { get; } + public float? FullValidMeanTokenAccuracy { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFineTuningJobCheckpointObject.cs b/src/Generated/Models/InternalFineTuningJobCheckpointObject.cs index 5cdd24ad8..8a9e3bf8c 100644 --- a/src/Generated/Models/InternalFineTuningJobCheckpointObject.cs +++ b/src/Generated/Models/InternalFineTuningJobCheckpointObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalFineTuningJobCheckpointObject : IEquatable { private readonly string _value; + private const string FineTuningJobCheckpointValue = "fine_tuning.job.checkpoint"; public InternalFineTuningJobCheckpointObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FineTuningJobCheckpointValue = "fine_tuning.job.checkpoint"; + _value = value; + } public static InternalFineTuningJobCheckpointObject FineTuningJobCheckpoint { get; } = new InternalFineTuningJobCheckpointObject(FineTuningJobCheckpointValue); + public static bool operator ==(InternalFineTuningJobCheckpointObject left, InternalFineTuningJobCheckpointObject right) => left.Equals(right); + public static bool operator !=(InternalFineTuningJobCheckpointObject left, InternalFineTuningJobCheckpointObject right) => !left.Equals(right); + public static implicit operator InternalFineTuningJobCheckpointObject(string value) => new InternalFineTuningJobCheckpointObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalFineTuningJobCheckpointObject other && Equals(other); + public bool Equals(InternalFineTuningJobCheckpointObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalFineTuningJobEventObject.cs b/src/Generated/Models/InternalFineTuningJobEventObject.cs index 04fdff4dc..1dec101d9 100644 --- a/src/Generated/Models/InternalFineTuningJobEventObject.cs +++ b/src/Generated/Models/InternalFineTuningJobEventObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalFineTuningJobEventObject : IEquatable { private readonly string _value; + private const string FineTuningJobEventValue = "fine_tuning.job.event"; public InternalFineTuningJobEventObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FineTuningJobEventValue = "fine_tuning.job.event"; + _value = value; + } public static InternalFineTuningJobEventObject FineTuningJobEvent { get; } = new InternalFineTuningJobEventObject(FineTuningJobEventValue); + public static bool operator ==(InternalFineTuningJobEventObject left, InternalFineTuningJobEventObject right) => left.Equals(right); + public static bool operator !=(InternalFineTuningJobEventObject left, InternalFineTuningJobEventObject right) => !left.Equals(right); + public static implicit operator InternalFineTuningJobEventObject(string value) => new InternalFineTuningJobEventObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalFineTuningJobEventObject other && Equals(other); + public bool Equals(InternalFineTuningJobEventObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalFineTuningJobObject.cs b/src/Generated/Models/InternalFineTuningJobObject.cs index b627e2945..1b11ef517 100644 --- a/src/Generated/Models/InternalFineTuningJobObject.cs +++ b/src/Generated/Models/InternalFineTuningJobObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalFineTuningJobObject : IEquatable { private readonly string _value; + private const string FineTuningJobValue = "fine_tuning.job"; public InternalFineTuningJobObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FineTuningJobValue = "fine_tuning.job"; + _value = value; + } public static InternalFineTuningJobObject FineTuningJob { get; } = new InternalFineTuningJobObject(FineTuningJobValue); + public static bool operator ==(InternalFineTuningJobObject left, InternalFineTuningJobObject right) => left.Equals(right); + public static bool operator !=(InternalFineTuningJobObject left, InternalFineTuningJobObject right) => !left.Equals(right); + public static implicit operator InternalFineTuningJobObject(string value) => new InternalFineTuningJobObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalFineTuningJobObject other && Equals(other); + public bool Equals(InternalFineTuningJobObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalFinetuneChatRequestInput.Serialization.cs b/src/Generated/Models/InternalFinetuneChatRequestInput.Serialization.cs index 946bb2d93..2f5a99d7b 100644 --- a/src/Generated/Models/InternalFinetuneChatRequestInput.Serialization.cs +++ b/src/Generated/Models/InternalFinetuneChatRequestInput.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.Chat; namespace OpenAI.FineTuning @@ -15,18 +16,23 @@ internal partial class InternalFinetuneChatRequestInput : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFinetuneChatRequestInput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("messages") != true && Optional.IsCollectionDefined(Messages)) + if (Optional.IsCollectionDefined(Messages) && _additionalBinaryDataProperties?.ContainsKey("messages") != true) { writer.WritePropertyName("messages"u8); writer.WriteStartArray(); - foreach (var item in Messages) + foreach (BinaryData item in Messages) { if (item == null) { @@ -34,7 +40,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M continue; } #if NET6_0_OR_GREATER - writer.WriteRawValue(item); + writer.WriteRawValue(item); #else using (JsonDocument document = JsonDocument.Parse(item)) { @@ -44,34 +50,34 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ChatTool item in Tools) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(ParallelToolCalls)) + if (Optional.IsDefined(ParallelToolCalls) && _additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true) { writer.WritePropertyName("parallel_tool_calls"u8); writer.WriteBooleanValue(ParallelToolCalls.Value); } - if (SerializedAdditionalRawData?.ContainsKey("functions") != true && Optional.IsCollectionDefined(Functions)) + if (Optional.IsCollectionDefined(Functions) && _additionalBinaryDataProperties?.ContainsKey("functions") != true) { writer.WritePropertyName("functions"u8); writer.WriteStartArray(); - foreach (var item in Functions) + foreach (ChatFunction item in Functions) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -79,7 +85,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -88,25 +94,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalFinetuneChatRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFinetuneChatRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFinetuneChatRequestInput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFinetuneChatRequestInput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFinetuneChatRequestInput(document.RootElement, options); } - internal static InternalFinetuneChatRequestInput DeserializeInternalFinetuneChatRequestInput(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFinetuneChatRequestInput DeserializeInternalFinetuneChatRequestInput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -115,18 +119,17 @@ internal static InternalFinetuneChatRequestInput DeserializeInternalFinetuneChat IList tools = default; bool? parallelToolCalls = default; IList functions = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("messages"u8)) + if (prop.NameEquals("messages"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { @@ -140,37 +143,37 @@ internal static InternalFinetuneChatRequestInput DeserializeInternalFinetuneChat messages = array; continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatTool.DeserializeChatTool(item, options)); } tools = array; continue; } - if (property.NameEquals("parallel_tool_calls"u8)) + if (prop.NameEquals("parallel_tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - parallelToolCalls = property.Value.GetBoolean(); + parallelToolCalls = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("functions"u8)) + if (prop.NameEquals("functions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ChatFunction.DeserializeChatFunction(item, options)); } @@ -179,18 +182,17 @@ internal static InternalFinetuneChatRequestInput DeserializeInternalFinetuneChat } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalFinetuneChatRequestInput(messages ?? new ChangeTrackingList(), tools ?? new ChangeTrackingList(), parallelToolCalls, functions ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalFinetuneChatRequestInput(messages ?? new ChangeTrackingList(), tools ?? new ChangeTrackingList(), parallelToolCalls, functions ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -200,15 +202,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalFinetuneChatRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFinetuneChatRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFinetuneChatRequestInput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFinetuneChatRequestInput(document.RootElement, options); } default: @@ -218,15 +221,20 @@ InternalFinetuneChatRequestInput IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFinetuneChatRequestInput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFinetuneChatRequestInput internalFinetuneChatRequestInput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFinetuneChatRequestInput(document.RootElement); + if (internalFinetuneChatRequestInput == null) + { + return null; + } + return BinaryContent.Create(internalFinetuneChatRequestInput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFinetuneChatRequestInput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFinetuneChatRequestInput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFinetuneChatRequestInput.cs b/src/Generated/Models/InternalFinetuneChatRequestInput.cs index b325ed536..6588ee146 100644 --- a/src/Generated/Models/InternalFinetuneChatRequestInput.cs +++ b/src/Generated/Models/InternalFinetuneChatRequestInput.cs @@ -4,13 +4,15 @@ using System; using System.Collections.Generic; +using OpenAI; using OpenAI.Chat; namespace OpenAI.FineTuning { internal partial class InternalFinetuneChatRequestInput { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalFinetuneChatRequestInput() { Messages = new ChangeTrackingList(); @@ -18,18 +20,27 @@ public InternalFinetuneChatRequestInput() Functions = new ChangeTrackingList(); } - internal InternalFinetuneChatRequestInput(IList messages, IList tools, bool? parallelToolCalls, IList functions, IDictionary serializedAdditionalRawData) + internal InternalFinetuneChatRequestInput(IList messages, IList tools, bool? parallelToolCalls, IList functions, IDictionary additionalBinaryDataProperties) { Messages = messages; Tools = tools; ParallelToolCalls = parallelToolCalls; Functions = functions; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList Messages { get; } + public IList Tools { get; } + public bool? ParallelToolCalls { get; set; } + public IList Functions { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFinetuneCompletionRequestInput.Serialization.cs b/src/Generated/Models/InternalFinetuneCompletionRequestInput.Serialization.cs index 5fbbb7472..30c684544 100644 --- a/src/Generated/Models/InternalFinetuneCompletionRequestInput.Serialization.cs +++ b/src/Generated/Models/InternalFinetuneCompletionRequestInput.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { @@ -14,26 +15,31 @@ internal partial class InternalFinetuneCompletionRequestInput : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFinetuneCompletionRequestInput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("prompt") != true && Optional.IsDefined(Prompt)) + if (Optional.IsDefined(Prompt) && _additionalBinaryDataProperties?.ContainsKey("prompt") != true) { writer.WritePropertyName("prompt"u8); writer.WriteStringValue(Prompt); } - if (SerializedAdditionalRawData?.ContainsKey("completion") != true && Optional.IsDefined(Completion)) + if (Optional.IsDefined(Completion) && _additionalBinaryDataProperties?.ContainsKey("completion") != true) { writer.WritePropertyName("completion"u8); writer.WriteStringValue(Completion); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter wri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter wri #endif } } - writer.WriteEndObject(); } - InternalFinetuneCompletionRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFinetuneCompletionRequestInput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFinetuneCompletionRequestInput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFinetuneCompletionRequestInput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFinetuneCompletionRequestInput(document.RootElement, options); } - internal static InternalFinetuneCompletionRequestInput DeserializeInternalFinetuneCompletionRequestInput(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFinetuneCompletionRequestInput DeserializeInternalFinetuneCompletionRequestInput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string prompt = default; string completion = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("prompt"u8)) + if (prop.NameEquals("prompt"u8)) { - prompt = property.Value.GetString(); + prompt = prop.Value.GetString(); continue; } - if (property.NameEquals("completion"u8)) + if (prop.NameEquals("completion"u8)) { - completion = property.Value.GetString(); + completion = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalFinetuneCompletionRequestInput(prompt, completion, serializedAdditionalRawData); + return new InternalFinetuneCompletionRequestInput(prompt, completion, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalFinetuneCompletionRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFinetuneCompletionRequestInput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFinetuneCompletionRequestInput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFinetuneCompletionRequestInput(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalFinetuneCompletionRequestInput IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFinetuneCompletionRequestInput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFinetuneCompletionRequestInput internalFinetuneCompletionRequestInput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFinetuneCompletionRequestInput(document.RootElement); + if (internalFinetuneCompletionRequestInput == null) + { + return null; + } + return BinaryContent.Create(internalFinetuneCompletionRequestInput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFinetuneCompletionRequestInput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFinetuneCompletionRequestInput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFinetuneCompletionRequestInput.cs b/src/Generated/Models/InternalFinetuneCompletionRequestInput.cs index 3e30640c6..77224a7f9 100644 --- a/src/Generated/Models/InternalFinetuneCompletionRequestInput.cs +++ b/src/Generated/Models/InternalFinetuneCompletionRequestInput.cs @@ -9,19 +9,27 @@ namespace OpenAI.FineTuning { internal partial class InternalFinetuneCompletionRequestInput { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalFinetuneCompletionRequestInput() { } - internal InternalFinetuneCompletionRequestInput(string prompt, string completion, IDictionary serializedAdditionalRawData) + internal InternalFinetuneCompletionRequestInput(string prompt, string completion, IDictionary additionalBinaryDataProperties) { Prompt = prompt; Completion = completion; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Prompt { get; set; } + public string Completion { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFunctionDefinition.Serialization.cs b/src/Generated/Models/InternalFunctionDefinition.Serialization.cs index 57335523d..1a1fb60f9 100644 --- a/src/Generated/Models/InternalFunctionDefinition.Serialization.cs +++ b/src/Generated/Models/InternalFunctionDefinition.Serialization.cs @@ -12,38 +12,35 @@ namespace OpenAI { internal partial class InternalFunctionDefinition : IJsonModel { + internal InternalFunctionDefinition() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFunctionDefinition)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(Description)) + if (Optional.IsDefined(Description) && _additionalBinaryDataProperties?.ContainsKey("description") != true) { writer.WritePropertyName("description"u8); writer.WriteStringValue(Description); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true && Optional.IsDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Parameters); -#else - using (JsonDocument document = JsonDocument.Parse(Parameters)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("strict") != true && Optional.IsDefined(Strict)) + if (Optional.IsDefined(Strict) && _additionalBinaryDataProperties?.ContainsKey("strict") != true) { if (Strict != null) { @@ -52,12 +49,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } else { - writer.WriteNull("strict"); + writer.WriteNull("strict"u8); } } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(Parameters) && _additionalBinaryDataProperties?.ContainsKey("parameters") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("parameters"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Parameters); +#else + using (JsonDocument document = JsonDocument.Parse(Parameters)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +74,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,80 +83,76 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - InternalFunctionDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFunctionDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFunctionDefinition JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFunctionDefinition)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFunctionDefinition(document.RootElement, options); } - internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string description = default; string name = default; - BinaryData parameters = default; bool? strict = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData parameters = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("description"u8)) + if (prop.NameEquals("description"u8)) { - description = property.Value.GetString(); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("parameters"u8)) + if (prop.NameEquals("strict"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + strict = null; continue; } - parameters = BinaryData.FromString(property.Value.GetRawText()); + strict = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("strict"u8)) + if (prop.NameEquals("parameters"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - strict = null; continue; } - strict = property.Value.GetBoolean(); + parameters = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalFunctionDefinition(description, name, parameters, strict, serializedAdditionalRawData); + return new InternalFunctionDefinition(description, name, strict, parameters, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -157,15 +162,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalFunctionDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFunctionDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFunctionDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFunctionDefinition(document.RootElement, options); } default: @@ -175,15 +181,20 @@ InternalFunctionDefinition IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFunctionDefinition FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFunctionDefinition internalFunctionDefinition) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFunctionDefinition(document.RootElement); + if (internalFunctionDefinition == null) + { + return null; + } + return BinaryContent.Create(internalFunctionDefinition, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFunctionDefinition(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFunctionDefinition(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFunctionDefinition.cs b/src/Generated/Models/InternalFunctionDefinition.cs index 9e385deb8..789b1cb92 100644 --- a/src/Generated/Models/InternalFunctionDefinition.cs +++ b/src/Generated/Models/InternalFunctionDefinition.cs @@ -9,7 +9,8 @@ namespace OpenAI { internal partial class InternalFunctionDefinition { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalFunctionDefinition(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,21 +18,25 @@ public InternalFunctionDefinition(string name) Name = name; } - internal InternalFunctionDefinition(string description, string name, BinaryData parameters, bool? strict, IDictionary serializedAdditionalRawData) + internal InternalFunctionDefinition(string description, string name, bool? strict, BinaryData parameters, IDictionary additionalBinaryDataProperties) { Description = description; Name = name; - Parameters = parameters; Strict = strict; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalFunctionDefinition() - { + Parameters = parameters; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Description { get; set; } + public string Name { get; set; } + public bool? Strict { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalFunctionParameters.Serialization.cs b/src/Generated/Models/InternalFunctionParameters.Serialization.cs index 4ab8c6f4c..cf2589d53 100644 --- a/src/Generated/Models/InternalFunctionParameters.Serialization.cs +++ b/src/Generated/Models/InternalFunctionParameters.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,18 +15,23 @@ internal partial class InternalFunctionParameters : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFunctionParameters)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); foreach (var item in AdditionalProperties) { writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -33,43 +39,40 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } #endif } - writer.WriteEndObject(); } - InternalFunctionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFunctionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalFunctionParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFunctionParameters)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFunctionParameters(document.RootElement, options); } - internal static InternalFunctionParameters DeserializeInternalFunctionParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalFunctionParameters DeserializeInternalFunctionParameters(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } - additionalProperties = additionalPropertiesDictionary; return new InternalFunctionParameters(additionalProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -79,15 +82,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalFunctionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFunctionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalFunctionParameters 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFunctionParameters(document.RootElement, options); } default: @@ -97,15 +101,20 @@ InternalFunctionParameters IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalFunctionParameters FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalFunctionParameters internalFunctionParameters) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalFunctionParameters(document.RootElement); + if (internalFunctionParameters == null) + { + return null; + } + return BinaryContent.Create(internalFunctionParameters, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalFunctionParameters(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalFunctionParameters(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalFunctionParameters.cs b/src/Generated/Models/InternalFunctionParameters.cs index 0320cf60c..67b1a19c7 100644 --- a/src/Generated/Models/InternalFunctionParameters.cs +++ b/src/Generated/Models/InternalFunctionParameters.cs @@ -4,21 +4,30 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalFunctionParameters { + private protected IDictionary _additionalBinaryDataProperties; + public InternalFunctionParameters() { - AdditionalProperties = new ChangeTrackingDictionary(); + _additionalBinaryDataProperties = new ChangeTrackingDictionary(); } internal InternalFunctionParameters(IDictionary additionalProperties) { - AdditionalProperties = additionalProperties; + _additionalBinaryDataProperties = additionalProperties; } - public IDictionary AdditionalProperties { get; } + public IDictionary AdditionalProperties => _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalIncludedRunStepProperty.cs b/src/Generated/Models/InternalIncludedRunStepProperty.cs index 3ae97f3d2..f401e03d3 100644 --- a/src/Generated/Models/InternalIncludedRunStepProperty.cs +++ b/src/Generated/Models/InternalIncludedRunStepProperty.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalIncludedRunStepProperty : IEquatable { private readonly string _value; + private const string FileSearchResultContentValue = "step_details.tool_calls[*].file_search.results[*].content"; public InternalIncludedRunStepProperty(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FileSearchResultContentValue = "step_details.tool_calls[*].file_search.results[*].content"; + _value = value; + } public static InternalIncludedRunStepProperty FileSearchResultContent { get; } = new InternalIncludedRunStepProperty(FileSearchResultContentValue); + public static bool operator ==(InternalIncludedRunStepProperty left, InternalIncludedRunStepProperty right) => left.Equals(right); + public static bool operator !=(InternalIncludedRunStepProperty left, InternalIncludedRunStepProperty right) => !left.Equals(right); + public static implicit operator InternalIncludedRunStepProperty(string value) => new InternalIncludedRunStepProperty(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalIncludedRunStepProperty other && Equals(other); + public bool Equals(InternalIncludedRunStepProperty other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListAssistantsResponse.Serialization.cs b/src/Generated/Models/InternalListAssistantsResponse.Serialization.cs index edbc8c764..4de8caa0c 100644 --- a/src/Generated/Models/InternalListAssistantsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListAssistantsResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListAssistantsResponse : IJsonModel { + internal InternalListAssistantsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListAssistantsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (Assistant item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod #endif } } - writer.WriteEndObject(); } - InternalListAssistantsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListAssistantsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListAssistantsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListAssistantsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListAssistantsResponse(document.RootElement, options); } - internal static InternalListAssistantsResponse DeserializeInternalListAssistantsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListAssistantsResponse DeserializeInternalListAssistantsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListAssistantsResponse DeserializeInternalListAssistants string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListAssistantsResponseObject(property.Value.GetString()); + @object = new InternalListAssistantsResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(Assistant.DeserializeAssistant(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListAssistantsResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - InternalListAssistantsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListAssistantsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListAssistantsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListAssistantsResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListAssistantsResponse IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListAssistantsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListAssistantsResponse internalListAssistantsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListAssistantsResponse(document.RootElement); + if (internalListAssistantsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListAssistantsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListAssistantsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListAssistantsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListAssistantsResponse.cs b/src/Generated/Models/InternalListAssistantsResponse.cs index 6ee4c4ccd..60504b4ef 100644 --- a/src/Generated/Models/InternalListAssistantsResponse.cs +++ b/src/Generated/Models/InternalListAssistantsResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListAssistantsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListAssistantsResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListAssistantsResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListAssistantsResponse(InternalListAssistantsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListAssistantsResponse(InternalListAssistantsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListAssistantsResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListAssistantsResponseObject Object { get; } = InternalListAssistantsResponseObject.List; + public InternalListAssistantsResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListAssistantsResponseObject.cs b/src/Generated/Models/InternalListAssistantsResponseObject.cs index 6d7350e78..3ee6613cc 100644 --- a/src/Generated/Models/InternalListAssistantsResponseObject.cs +++ b/src/Generated/Models/InternalListAssistantsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalListAssistantsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListAssistantsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListAssistantsResponseObject List { get; } = new InternalListAssistantsResponseObject(ListValue); + public static bool operator ==(InternalListAssistantsResponseObject left, InternalListAssistantsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListAssistantsResponseObject left, InternalListAssistantsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListAssistantsResponseObject(string value) => new InternalListAssistantsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListAssistantsResponseObject other && Equals(other); + public bool Equals(InternalListAssistantsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListBatchesResponse.Serialization.cs b/src/Generated/Models/InternalListBatchesResponse.Serialization.cs index 432479b4b..b2a0325c6 100644 --- a/src/Generated/Models/InternalListBatchesResponse.Serialization.cs +++ b/src/Generated/Models/InternalListBatchesResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Batch { internal partial class InternalListBatchesResponse : IJsonModel { + internal InternalListBatchesResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListBatchesResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (_additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (InternalBatchJob item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true && Optional.IsDefined(FirstId)) + if (Optional.IsDefined(FirstId) && _additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true && Optional.IsDefined(LastId)) + if (Optional.IsDefined(LastId) && _additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,88 +80,84 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - InternalListBatchesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListBatchesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListBatchesResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListBatchesResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListBatchesResponse(document.RootElement, options); } - internal static InternalListBatchesResponse DeserializeInternalListBatchesResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListBatchesResponse DeserializeInternalListBatchesResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList data = default; + IList data = default; string firstId = default; string lastId = default; bool hasMore = default; InternalListBatchesResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalBatchJob.DeserializeInternalBatchJob(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListBatchesResponseObject(property.Value.GetString()); + @object = new InternalListBatchesResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListBatchesResponse( data, firstId, lastId, hasMore, @object, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalListBatchesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListBatchesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListBatchesResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListBatchesResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListBatchesResponse IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListBatchesResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListBatchesResponse internalListBatchesResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListBatchesResponse(document.RootElement); + if (internalListBatchesResponse == null) + { + return null; + } + return BinaryContent.Create(internalListBatchesResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListBatchesResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListBatchesResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListBatchesResponse.cs b/src/Generated/Models/InternalListBatchesResponse.cs index c81c672cc..588ef3f71 100644 --- a/src/Generated/Models/InternalListBatchesResponse.cs +++ b/src/Generated/Models/InternalListBatchesResponse.cs @@ -10,33 +10,38 @@ namespace OpenAI.Batch { internal partial class InternalListBatchesResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalListBatchesResponse(IEnumerable data, bool hasMore) { - Argument.AssertNotNull(data, nameof(data)); - Data = data.ToList(); HasMore = hasMore; } - internal InternalListBatchesResponse(IReadOnlyList data, string firstId, string lastId, bool hasMore, InternalListBatchesResponseObject @object, IDictionary serializedAdditionalRawData) + internal InternalListBatchesResponse(IList data, string firstId, string lastId, bool hasMore, InternalListBatchesResponseObject @object, IDictionary additionalBinaryDataProperties) { Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalListBatchesResponse() - { - } + public IList Data { get; } - public IReadOnlyList Data { get; } public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } - public InternalListBatchesResponseObject Object { get; } = InternalListBatchesResponseObject.List; + + public InternalListBatchesResponseObject Object { get; } = "list"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListBatchesResponseObject.cs b/src/Generated/Models/InternalListBatchesResponseObject.cs index 3f562b70d..e63aa1089 100644 --- a/src/Generated/Models/InternalListBatchesResponseObject.cs +++ b/src/Generated/Models/InternalListBatchesResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Batch { internal readonly partial struct InternalListBatchesResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListBatchesResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListBatchesResponseObject List { get; } = new InternalListBatchesResponseObject(ListValue); + public static bool operator ==(InternalListBatchesResponseObject left, InternalListBatchesResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListBatchesResponseObject left, InternalListBatchesResponseObject right) => !left.Equals(right); + public static implicit operator InternalListBatchesResponseObject(string value) => new InternalListBatchesResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListBatchesResponseObject other && Equals(other); + public bool Equals(InternalListBatchesResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListFilesInVectorStoreBatchRequestOrder.cs b/src/Generated/Models/InternalListFilesInVectorStoreBatchRequestOrder.cs index 3cabf6088..621f99ed5 100644 --- a/src/Generated/Models/InternalListFilesInVectorStoreBatchRequestOrder.cs +++ b/src/Generated/Models/InternalListFilesInVectorStoreBatchRequestOrder.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalListFilesInVectorStoreBatchRequestOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public InternalListFilesInVectorStoreBatchRequestOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AscValue = "asc"; - private const string DescValue = "desc"; + _value = value; + } public static InternalListFilesInVectorStoreBatchRequestOrder Asc { get; } = new InternalListFilesInVectorStoreBatchRequestOrder(AscValue); + public static InternalListFilesInVectorStoreBatchRequestOrder Desc { get; } = new InternalListFilesInVectorStoreBatchRequestOrder(DescValue); + public static bool operator ==(InternalListFilesInVectorStoreBatchRequestOrder left, InternalListFilesInVectorStoreBatchRequestOrder right) => left.Equals(right); + public static bool operator !=(InternalListFilesInVectorStoreBatchRequestOrder left, InternalListFilesInVectorStoreBatchRequestOrder right) => !left.Equals(right); + public static implicit operator InternalListFilesInVectorStoreBatchRequestOrder(string value) => new InternalListFilesInVectorStoreBatchRequestOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListFilesInVectorStoreBatchRequestOrder other && Equals(other); + public bool Equals(InternalListFilesInVectorStoreBatchRequestOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListFilesResponseObject.cs b/src/Generated/Models/InternalListFilesResponseObject.cs index 2b578ea18..2fa2419c8 100644 --- a/src/Generated/Models/InternalListFilesResponseObject.cs +++ b/src/Generated/Models/InternalListFilesResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalListFilesResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListFilesResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListFilesResponseObject List { get; } = new InternalListFilesResponseObject(ListValue); + public static bool operator ==(InternalListFilesResponseObject left, InternalListFilesResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListFilesResponseObject left, InternalListFilesResponseObject right) => !left.Equals(right); + public static implicit operator InternalListFilesResponseObject(string value) => new InternalListFilesResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListFilesResponseObject other && Equals(other); + public bool Equals(InternalListFilesResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.Serialization.cs b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.Serialization.cs index 9078810a3..ecc8440c6 100644 --- a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.Serialization.cs @@ -7,36 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalListFineTuningJobCheckpointsResponse : IJsonModel { + internal InternalListFineTuningJobCheckpointsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListFineTuningJobCheckpointsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (_additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (InternalFineTuningJobCheckpoint item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true && Optional.IsDefined(FirstId)) + if (Optional.IsDefined(FirstId) && _additionalBinaryDataProperties?.ContainsKey("first_id") != true) { if (FirstId != null) { @@ -45,10 +55,10 @@ void IJsonModel.Write(Utf8JsonWrit } else { - writer.WriteNull("first_id"); + writer.WriteNull("firstId"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true && Optional.IsDefined(LastId)) + if (Optional.IsDefined(LastId) && _additionalBinaryDataProperties?.ContainsKey("last_id") != true) { if (LastId != null) { @@ -57,17 +67,17 @@ void IJsonModel.Write(Utf8JsonWrit } else { - writer.WriteNull("last_id"); + writer.WriteNull("lastId"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -75,7 +85,7 @@ void IJsonModel.Write(Utf8JsonWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -84,98 +94,94 @@ void IJsonModel.Write(Utf8JsonWrit #endif } } - writer.WriteEndObject(); } - InternalListFineTuningJobCheckpointsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListFineTuningJobCheckpointsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListFineTuningJobCheckpointsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListFineTuningJobCheckpointsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListFineTuningJobCheckpointsResponse(document.RootElement, options); } - internal static InternalListFineTuningJobCheckpointsResponse DeserializeInternalListFineTuningJobCheckpointsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListFineTuningJobCheckpointsResponse DeserializeInternalListFineTuningJobCheckpointsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList data = default; + IList data = default; InternalListFineTuningJobCheckpointsResponseObject @object = default; string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalFineTuningJobCheckpoint.DeserializeInternalFineTuningJobCheckpoint(item, options)); } data = array; continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListFineTuningJobCheckpointsResponseObject(property.Value.GetString()); + @object = new InternalListFineTuningJobCheckpointsResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { firstId = null; continue; } - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { lastId = null; continue; } - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListFineTuningJobCheckpointsResponse( data, @object, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -185,15 +191,16 @@ BinaryData IPersistableModel.Write } } - InternalListFineTuningJobCheckpointsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListFineTuningJobCheckpointsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListFineTuningJobCheckpointsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListFineTuningJobCheckpointsResponse(document.RootElement, options); } default: @@ -203,15 +210,20 @@ InternalListFineTuningJobCheckpointsResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListFineTuningJobCheckpointsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListFineTuningJobCheckpointsResponse internalListFineTuningJobCheckpointsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListFineTuningJobCheckpointsResponse(document.RootElement); + if (internalListFineTuningJobCheckpointsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListFineTuningJobCheckpointsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListFineTuningJobCheckpointsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListFineTuningJobCheckpointsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.cs b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.cs index f96a3d96a..48431f1c9 100644 --- a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.cs +++ b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponse.cs @@ -10,34 +10,38 @@ namespace OpenAI.FineTuning { internal partial class InternalListFineTuningJobCheckpointsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalListFineTuningJobCheckpointsResponse(IEnumerable data, bool hasMore) { - Argument.AssertNotNull(data, nameof(data)); - Data = data.ToList(); HasMore = hasMore; } - internal InternalListFineTuningJobCheckpointsResponse(IReadOnlyList data, InternalListFineTuningJobCheckpointsResponseObject @object, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListFineTuningJobCheckpointsResponse(IList data, InternalListFineTuningJobCheckpointsResponseObject @object, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Data = data; Object = @object; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalListFineTuningJobCheckpointsResponse() - { - } + public IList Data { get; } - public IReadOnlyList Data { get; } - public InternalListFineTuningJobCheckpointsResponseObject Object { get; } = InternalListFineTuningJobCheckpointsResponseObject.List; + public InternalListFineTuningJobCheckpointsResponseObject Object { get; } = "list"; public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponseObject.cs b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponseObject.cs index 8a9ca04a3..4238f5ef6 100644 --- a/src/Generated/Models/InternalListFineTuningJobCheckpointsResponseObject.cs +++ b/src/Generated/Models/InternalListFineTuningJobCheckpointsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalListFineTuningJobCheckpointsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListFineTuningJobCheckpointsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListFineTuningJobCheckpointsResponseObject List { get; } = new InternalListFineTuningJobCheckpointsResponseObject(ListValue); + public static bool operator ==(InternalListFineTuningJobCheckpointsResponseObject left, InternalListFineTuningJobCheckpointsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListFineTuningJobCheckpointsResponseObject left, InternalListFineTuningJobCheckpointsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListFineTuningJobCheckpointsResponseObject(string value) => new InternalListFineTuningJobCheckpointsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListFineTuningJobCheckpointsResponseObject other && Equals(other); + public bool Equals(InternalListFineTuningJobCheckpointsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListFineTuningJobEventsResponse.Serialization.cs b/src/Generated/Models/InternalListFineTuningJobEventsResponse.Serialization.cs index 14fbb61f6..e700b47fd 100644 --- a/src/Generated/Models/InternalListFineTuningJobEventsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListFineTuningJobEventsResponse.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalListFineTuningJobEventsResponse : IJsonModel { + internal InternalListFineTuningJobEventsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListFineTuningJobEventsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (_additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (FineTuningJobEvent item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter wr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,70 +70,66 @@ void IJsonModel.Write(Utf8JsonWriter wr #endif } } - writer.WriteEndObject(); } - InternalListFineTuningJobEventsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListFineTuningJobEventsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListFineTuningJobEventsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListFineTuningJobEventsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListFineTuningJobEventsResponse(document.RootElement, options); } - internal static InternalListFineTuningJobEventsResponse DeserializeInternalListFineTuningJobEventsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListFineTuningJobEventsResponse DeserializeInternalListFineTuningJobEventsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } bool hasMore = default; - IReadOnlyList data = default; + IList data = default; InternalListFineTuningJobEventsResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(FineTuningJobEvent.DeserializeFineTuningJobEvent(item, options)); } data = array; continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListFineTuningJobEventsResponseObject(property.Value.GetString()); + @object = new InternalListFineTuningJobEventsResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalListFineTuningJobEventsResponse(hasMore, data, @object, serializedAdditionalRawData); + return new InternalListFineTuningJobEventsResponse(hasMore, data, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -133,15 +139,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalListFineTuningJobEventsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListFineTuningJobEventsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListFineTuningJobEventsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListFineTuningJobEventsResponse(document.RootElement, options); } default: @@ -151,15 +158,20 @@ InternalListFineTuningJobEventsResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListFineTuningJobEventsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListFineTuningJobEventsResponse internalListFineTuningJobEventsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListFineTuningJobEventsResponse(document.RootElement); + if (internalListFineTuningJobEventsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListFineTuningJobEventsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListFineTuningJobEventsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListFineTuningJobEventsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListFineTuningJobEventsResponse.cs b/src/Generated/Models/InternalListFineTuningJobEventsResponse.cs index e8e12b311..c34113f0d 100644 --- a/src/Generated/Models/InternalListFineTuningJobEventsResponse.cs +++ b/src/Generated/Models/InternalListFineTuningJobEventsResponse.cs @@ -10,29 +10,32 @@ namespace OpenAI.FineTuning { internal partial class InternalListFineTuningJobEventsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalListFineTuningJobEventsResponse(bool hasMore, IEnumerable data) { - Argument.AssertNotNull(data, nameof(data)); - HasMore = hasMore; Data = data.ToList(); } - internal InternalListFineTuningJobEventsResponse(bool hasMore, IReadOnlyList data, InternalListFineTuningJobEventsResponseObject @object, IDictionary serializedAdditionalRawData) + internal InternalListFineTuningJobEventsResponse(bool hasMore, IList data, InternalListFineTuningJobEventsResponseObject @object, IDictionary additionalBinaryDataProperties) { HasMore = hasMore; Data = data; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalListFineTuningJobEventsResponse() + public bool HasMore { get; } + + public IList Data { get; } + + public InternalListFineTuningJobEventsResponseObject Object { get; } = "list"; + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public bool HasMore { get; } - public IReadOnlyList Data { get; } - public InternalListFineTuningJobEventsResponseObject Object { get; } = InternalListFineTuningJobEventsResponseObject.List; } } diff --git a/src/Generated/Models/InternalListFineTuningJobEventsResponseObject.cs b/src/Generated/Models/InternalListFineTuningJobEventsResponseObject.cs index 5f4aa8afb..2f75c90d9 100644 --- a/src/Generated/Models/InternalListFineTuningJobEventsResponseObject.cs +++ b/src/Generated/Models/InternalListFineTuningJobEventsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalListFineTuningJobEventsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListFineTuningJobEventsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListFineTuningJobEventsResponseObject List { get; } = new InternalListFineTuningJobEventsResponseObject(ListValue); + public static bool operator ==(InternalListFineTuningJobEventsResponseObject left, InternalListFineTuningJobEventsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListFineTuningJobEventsResponseObject left, InternalListFineTuningJobEventsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListFineTuningJobEventsResponseObject(string value) => new InternalListFineTuningJobEventsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListFineTuningJobEventsResponseObject other && Equals(other); + public bool Equals(InternalListFineTuningJobEventsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListMessagesResponse.Serialization.cs b/src/Generated/Models/InternalListMessagesResponse.Serialization.cs index f91fc9dec..691a66723 100644 --- a/src/Generated/Models/InternalListMessagesResponse.Serialization.cs +++ b/src/Generated/Models/InternalListMessagesResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListMessagesResponse : IJsonModel { + internal InternalListMessagesResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListMessagesResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (ThreadMessage item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - InternalListMessagesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListMessagesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListMessagesResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListMessagesResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListMessagesResponse(document.RootElement, options); } - internal static InternalListMessagesResponse DeserializeInternalListMessagesResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListMessagesResponse DeserializeInternalListMessagesResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListMessagesResponse DeserializeInternalListMessagesResp string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListMessagesResponseObject(property.Value.GetString()); + @object = new InternalListMessagesResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ThreadMessage.DeserializeThreadMessage(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListMessagesResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalListMessagesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListMessagesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListMessagesResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListMessagesResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListMessagesResponse IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListMessagesResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListMessagesResponse internalListMessagesResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListMessagesResponse(document.RootElement); + if (internalListMessagesResponse == null) + { + return null; + } + return BinaryContent.Create(internalListMessagesResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListMessagesResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListMessagesResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListMessagesResponse.cs b/src/Generated/Models/InternalListMessagesResponse.cs index 8fd5be212..5f0381ef6 100644 --- a/src/Generated/Models/InternalListMessagesResponse.cs +++ b/src/Generated/Models/InternalListMessagesResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListMessagesResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListMessagesResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListMessagesResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListMessagesResponse(InternalListMessagesResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListMessagesResponse(InternalListMessagesResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListMessagesResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListMessagesResponseObject Object { get; } = InternalListMessagesResponseObject.List; + public InternalListMessagesResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListMessagesResponseObject.cs b/src/Generated/Models/InternalListMessagesResponseObject.cs index 44e0d2aba..dc6c8b82d 100644 --- a/src/Generated/Models/InternalListMessagesResponseObject.cs +++ b/src/Generated/Models/InternalListMessagesResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalListMessagesResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListMessagesResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListMessagesResponseObject List { get; } = new InternalListMessagesResponseObject(ListValue); + public static bool operator ==(InternalListMessagesResponseObject left, InternalListMessagesResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListMessagesResponseObject left, InternalListMessagesResponseObject right) => !left.Equals(right); + public static implicit operator InternalListMessagesResponseObject(string value) => new InternalListMessagesResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListMessagesResponseObject other && Equals(other); + public bool Equals(InternalListMessagesResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListModelsResponseObject.cs b/src/Generated/Models/InternalListModelsResponseObject.cs index 29abbc2c7..dae3553c0 100644 --- a/src/Generated/Models/InternalListModelsResponseObject.cs +++ b/src/Generated/Models/InternalListModelsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Models { internal readonly partial struct InternalListModelsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListModelsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListModelsResponseObject List { get; } = new InternalListModelsResponseObject(ListValue); + public static bool operator ==(InternalListModelsResponseObject left, InternalListModelsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListModelsResponseObject left, InternalListModelsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListModelsResponseObject(string value) => new InternalListModelsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListModelsResponseObject other && Equals(other); + public bool Equals(InternalListModelsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.Serialization.cs b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.Serialization.cs index bde114de7..cfa70a193 100644 --- a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class InternalListPaginatedFineTuningJobsResponse : IJsonModel { + internal InternalListPaginatedFineTuningJobsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListPaginatedFineTuningJobsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (_additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (FineTuningJob item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,70 +70,66 @@ void IJsonModel.Write(Utf8JsonWrite #endif } } - writer.WriteEndObject(); } - InternalListPaginatedFineTuningJobsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListPaginatedFineTuningJobsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListPaginatedFineTuningJobsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListPaginatedFineTuningJobsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListPaginatedFineTuningJobsResponse(document.RootElement, options); } - internal static InternalListPaginatedFineTuningJobsResponse DeserializeInternalListPaginatedFineTuningJobsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListPaginatedFineTuningJobsResponse DeserializeInternalListPaginatedFineTuningJobsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList data = default; + IList data = default; bool hasMore = default; InternalListPaginatedFineTuningJobsResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(FineTuningJob.DeserializeFineTuningJob(item, options)); } data = array; continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListPaginatedFineTuningJobsResponseObject(property.Value.GetString()); + @object = new InternalListPaginatedFineTuningJobsResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalListPaginatedFineTuningJobsResponse(data, hasMore, @object, serializedAdditionalRawData); + return new InternalListPaginatedFineTuningJobsResponse(data, hasMore, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -133,15 +139,16 @@ BinaryData IPersistableModel.Write( } } - InternalListPaginatedFineTuningJobsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListPaginatedFineTuningJobsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListPaginatedFineTuningJobsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListPaginatedFineTuningJobsResponse(document.RootElement, options); } default: @@ -151,15 +158,20 @@ InternalListPaginatedFineTuningJobsResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListPaginatedFineTuningJobsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListPaginatedFineTuningJobsResponse internalListPaginatedFineTuningJobsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListPaginatedFineTuningJobsResponse(document.RootElement); + if (internalListPaginatedFineTuningJobsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListPaginatedFineTuningJobsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListPaginatedFineTuningJobsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListPaginatedFineTuningJobsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.cs b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.cs index 3789ce4e4..d063d6e4c 100644 --- a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.cs +++ b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponse.cs @@ -10,29 +10,32 @@ namespace OpenAI.FineTuning { internal partial class InternalListPaginatedFineTuningJobsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalListPaginatedFineTuningJobsResponse(IEnumerable data, bool hasMore) { - Argument.AssertNotNull(data, nameof(data)); - Data = data.ToList(); HasMore = hasMore; } - internal InternalListPaginatedFineTuningJobsResponse(IReadOnlyList data, bool hasMore, InternalListPaginatedFineTuningJobsResponseObject @object, IDictionary serializedAdditionalRawData) + internal InternalListPaginatedFineTuningJobsResponse(IList data, bool hasMore, InternalListPaginatedFineTuningJobsResponseObject @object, IDictionary additionalBinaryDataProperties) { Data = data; HasMore = hasMore; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalListPaginatedFineTuningJobsResponse() - { - } + public IList Data { get; } - public IReadOnlyList Data { get; } public bool HasMore { get; } - public InternalListPaginatedFineTuningJobsResponseObject Object { get; } = InternalListPaginatedFineTuningJobsResponseObject.List; + + public InternalListPaginatedFineTuningJobsResponseObject Object { get; } = "list"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponseObject.cs b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponseObject.cs index b9dcd5fb9..4bc6eed4d 100644 --- a/src/Generated/Models/InternalListPaginatedFineTuningJobsResponseObject.cs +++ b/src/Generated/Models/InternalListPaginatedFineTuningJobsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.FineTuning { internal readonly partial struct InternalListPaginatedFineTuningJobsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListPaginatedFineTuningJobsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListPaginatedFineTuningJobsResponseObject List { get; } = new InternalListPaginatedFineTuningJobsResponseObject(ListValue); + public static bool operator ==(InternalListPaginatedFineTuningJobsResponseObject left, InternalListPaginatedFineTuningJobsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListPaginatedFineTuningJobsResponseObject left, InternalListPaginatedFineTuningJobsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListPaginatedFineTuningJobsResponseObject(string value) => new InternalListPaginatedFineTuningJobsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListPaginatedFineTuningJobsResponseObject other && Equals(other); + public bool Equals(InternalListPaginatedFineTuningJobsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListRunStepsResponse.Serialization.cs b/src/Generated/Models/InternalListRunStepsResponse.Serialization.cs index 74e2033af..568099227 100644 --- a/src/Generated/Models/InternalListRunStepsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListRunStepsResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListRunStepsResponse : IJsonModel { + internal InternalListRunStepsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListRunStepsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (RunStep item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - InternalListRunStepsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListRunStepsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListRunStepsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListRunStepsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListRunStepsResponse(document.RootElement, options); } - internal static InternalListRunStepsResponse DeserializeInternalListRunStepsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListRunStepsResponse DeserializeInternalListRunStepsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListRunStepsResponse DeserializeInternalListRunStepsResp string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListRunStepsResponseObject(property.Value.GetString()); + @object = new InternalListRunStepsResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(RunStep.DeserializeRunStep(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListRunStepsResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalListRunStepsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListRunStepsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListRunStepsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListRunStepsResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListRunStepsResponse IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListRunStepsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListRunStepsResponse internalListRunStepsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListRunStepsResponse(document.RootElement); + if (internalListRunStepsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListRunStepsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListRunStepsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListRunStepsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListRunStepsResponse.cs b/src/Generated/Models/InternalListRunStepsResponse.cs index 4ef3eb223..b335f2f9d 100644 --- a/src/Generated/Models/InternalListRunStepsResponse.cs +++ b/src/Generated/Models/InternalListRunStepsResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListRunStepsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListRunStepsResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListRunStepsResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListRunStepsResponse(InternalListRunStepsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListRunStepsResponse(InternalListRunStepsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListRunStepsResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListRunStepsResponseObject Object { get; } = InternalListRunStepsResponseObject.List; + public InternalListRunStepsResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListRunStepsResponseObject.cs b/src/Generated/Models/InternalListRunStepsResponseObject.cs index c554f8ae4..a146511d3 100644 --- a/src/Generated/Models/InternalListRunStepsResponseObject.cs +++ b/src/Generated/Models/InternalListRunStepsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalListRunStepsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListRunStepsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListRunStepsResponseObject List { get; } = new InternalListRunStepsResponseObject(ListValue); + public static bool operator ==(InternalListRunStepsResponseObject left, InternalListRunStepsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListRunStepsResponseObject left, InternalListRunStepsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListRunStepsResponseObject(string value) => new InternalListRunStepsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListRunStepsResponseObject other && Equals(other); + public bool Equals(InternalListRunStepsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListRunsResponse.Serialization.cs b/src/Generated/Models/InternalListRunsResponse.Serialization.cs index 049905e5d..a18bb7c40 100644 --- a/src/Generated/Models/InternalListRunsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListRunsResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListRunsResponse : IJsonModel { + internal InternalListRunsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListRunsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (ThreadRun item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead #endif } } - writer.WriteEndObject(); } - InternalListRunsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListRunsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListRunsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListRunsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListRunsResponse(document.RootElement, options); } - internal static InternalListRunsResponse DeserializeInternalListRunsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListRunsResponse DeserializeInternalListRunsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListRunsResponse DeserializeInternalListRunsResponse(Jso string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListRunsResponseObject(property.Value.GetString()); + @object = new InternalListRunsResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ThreadRun.DeserializeThreadRun(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListRunsResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - InternalListRunsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListRunsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListRunsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListRunsResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListRunsResponse IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListRunsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListRunsResponse internalListRunsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListRunsResponse(document.RootElement); + if (internalListRunsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListRunsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListRunsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListRunsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListRunsResponse.cs b/src/Generated/Models/InternalListRunsResponse.cs index 4f10784e6..c4c91c9e4 100644 --- a/src/Generated/Models/InternalListRunsResponse.cs +++ b/src/Generated/Models/InternalListRunsResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListRunsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListRunsResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListRunsResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListRunsResponse(InternalListRunsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListRunsResponse(InternalListRunsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListRunsResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListRunsResponseObject Object { get; } = InternalListRunsResponseObject.List; + public InternalListRunsResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListRunsResponseObject.cs b/src/Generated/Models/InternalListRunsResponseObject.cs index 68d723f1c..353b74b7b 100644 --- a/src/Generated/Models/InternalListRunsResponseObject.cs +++ b/src/Generated/Models/InternalListRunsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalListRunsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListRunsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListRunsResponseObject List { get; } = new InternalListRunsResponseObject(ListValue); + public static bool operator ==(InternalListRunsResponseObject left, InternalListRunsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListRunsResponseObject left, InternalListRunsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListRunsResponseObject(string value) => new InternalListRunsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListRunsResponseObject other && Equals(other); + public bool Equals(InternalListRunsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListThreadsResponse.Serialization.cs b/src/Generated/Models/InternalListThreadsResponse.Serialization.cs index 9a4ec1998..deba50bb2 100644 --- a/src/Generated/Models/InternalListThreadsResponse.Serialization.cs +++ b/src/Generated/Models/InternalListThreadsResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListThreadsResponse : IJsonModel { + internal InternalListThreadsResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListThreadsResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (AssistantThread item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - InternalListThreadsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListThreadsResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListThreadsResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListThreadsResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListThreadsResponse(document.RootElement, options); } - internal static InternalListThreadsResponse DeserializeInternalListThreadsResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListThreadsResponse DeserializeInternalListThreadsResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListThreadsResponse DeserializeInternalListThreadsRespon string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListThreadsResponseObject(property.Value.GetString()); + @object = new InternalListThreadsResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(AssistantThread.DeserializeAssistantThread(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListThreadsResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalListThreadsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListThreadsResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListThreadsResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListThreadsResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListThreadsResponse IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListThreadsResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListThreadsResponse internalListThreadsResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListThreadsResponse(document.RootElement); + if (internalListThreadsResponse == null) + { + return null; + } + return BinaryContent.Create(internalListThreadsResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListThreadsResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListThreadsResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListThreadsResponse.cs b/src/Generated/Models/InternalListThreadsResponse.cs index 0424339fa..ae84cfdbf 100644 --- a/src/Generated/Models/InternalListThreadsResponse.cs +++ b/src/Generated/Models/InternalListThreadsResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalListThreadsResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListThreadsResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListThreadsResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListThreadsResponse(InternalListThreadsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListThreadsResponse(InternalListThreadsResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListThreadsResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListThreadsResponseObject Object { get; } = InternalListThreadsResponseObject.List; + public InternalListThreadsResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListThreadsResponseObject.cs b/src/Generated/Models/InternalListThreadsResponseObject.cs index 8fc2b64bf..7bb19f64a 100644 --- a/src/Generated/Models/InternalListThreadsResponseObject.cs +++ b/src/Generated/Models/InternalListThreadsResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalListThreadsResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListThreadsResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListThreadsResponseObject List { get; } = new InternalListThreadsResponseObject(ListValue); + public static bool operator ==(InternalListThreadsResponseObject left, InternalListThreadsResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListThreadsResponseObject left, InternalListThreadsResponseObject right) => !left.Equals(right); + public static implicit operator InternalListThreadsResponseObject(string value) => new InternalListThreadsResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListThreadsResponseObject other && Equals(other); + public bool Equals(InternalListThreadsResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListVectorStoreFilesResponse.Serialization.cs b/src/Generated/Models/InternalListVectorStoreFilesResponse.Serialization.cs index 3b5f44ef5..8d2b5fdf2 100644 --- a/src/Generated/Models/InternalListVectorStoreFilesResponse.Serialization.cs +++ b/src/Generated/Models/InternalListVectorStoreFilesResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalListVectorStoreFilesResponse : IJsonModel { + internal InternalListVectorStoreFilesResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListVectorStoreFilesResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (VectorStoreFileAssociation item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter write } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter write #endif } } - writer.WriteEndObject(); } - InternalListVectorStoreFilesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListVectorStoreFilesResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListVectorStoreFilesResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListVectorStoreFilesResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListVectorStoreFilesResponse(document.RootElement, options); } - internal static InternalListVectorStoreFilesResponse DeserializeInternalListVectorStoreFilesResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListVectorStoreFilesResponse DeserializeInternalListVectorStoreFilesResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListVectorStoreFilesResponse DeserializeInternalListVect string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListVectorStoreFilesResponseObject(property.Value.GetString()); + @object = new InternalListVectorStoreFilesResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(VectorStoreFileAssociation.DeserializeVectorStoreFileAssociation(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListVectorStoreFilesResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - InternalListVectorStoreFilesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListVectorStoreFilesResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListVectorStoreFilesResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListVectorStoreFilesResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListVectorStoreFilesResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListVectorStoreFilesResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListVectorStoreFilesResponse internalListVectorStoreFilesResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListVectorStoreFilesResponse(document.RootElement); + if (internalListVectorStoreFilesResponse == null) + { + return null; + } + return BinaryContent.Create(internalListVectorStoreFilesResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListVectorStoreFilesResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListVectorStoreFilesResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListVectorStoreFilesResponse.cs b/src/Generated/Models/InternalListVectorStoreFilesResponse.cs index cef502099..e5ea3d8a6 100644 --- a/src/Generated/Models/InternalListVectorStoreFilesResponse.cs +++ b/src/Generated/Models/InternalListVectorStoreFilesResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalListVectorStoreFilesResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListVectorStoreFilesResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListVectorStoreFilesResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListVectorStoreFilesResponse(InternalListVectorStoreFilesResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListVectorStoreFilesResponse(InternalListVectorStoreFilesResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListVectorStoreFilesResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListVectorStoreFilesResponseObject Object { get; } = InternalListVectorStoreFilesResponseObject.List; + public InternalListVectorStoreFilesResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListVectorStoreFilesResponseObject.cs b/src/Generated/Models/InternalListVectorStoreFilesResponseObject.cs index bc320af37..936f76205 100644 --- a/src/Generated/Models/InternalListVectorStoreFilesResponseObject.cs +++ b/src/Generated/Models/InternalListVectorStoreFilesResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalListVectorStoreFilesResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListVectorStoreFilesResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListVectorStoreFilesResponseObject List { get; } = new InternalListVectorStoreFilesResponseObject(ListValue); + public static bool operator ==(InternalListVectorStoreFilesResponseObject left, InternalListVectorStoreFilesResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListVectorStoreFilesResponseObject left, InternalListVectorStoreFilesResponseObject right) => !left.Equals(right); + public static implicit operator InternalListVectorStoreFilesResponseObject(string value) => new InternalListVectorStoreFilesResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListVectorStoreFilesResponseObject other && Equals(other); + public bool Equals(InternalListVectorStoreFilesResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalListVectorStoresResponse.Serialization.cs b/src/Generated/Models/InternalListVectorStoresResponse.Serialization.cs index e01ffb73e..15a375b63 100644 --- a/src/Generated/Models/InternalListVectorStoresResponse.Serialization.cs +++ b/src/Generated/Models/InternalListVectorStoresResponse.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalListVectorStoresResponse : IJsonModel { + internal InternalListVectorStoresResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalListVectorStoresResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("data") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("data") != true) { writer.WritePropertyName("data"u8); writer.WriteStartArray(); - foreach (var item in Data) + foreach (VectorStore item in Data) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("first_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("first_id") != true) { writer.WritePropertyName("first_id"u8); writer.WriteStringValue(FirstId); } - if (SerializedAdditionalRawData?.ContainsKey("last_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_id") != true) { writer.WritePropertyName("last_id"u8); writer.WriteStringValue(LastId); } - if (SerializedAdditionalRawData?.ContainsKey("has_more") != true) + if (_additionalBinaryDataProperties?.ContainsKey("has_more") != true) { writer.WritePropertyName("has_more"u8); writer.WriteBooleanValue(HasMore); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,25 +80,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalListVectorStoresResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalListVectorStoresResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalListVectorStoresResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalListVectorStoresResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalListVectorStoresResponse(document.RootElement, options); } - internal static InternalListVectorStoresResponse DeserializeInternalListVectorStoresResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalListVectorStoresResponse DeserializeInternalListVectorStoresResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -98,60 +106,58 @@ internal static InternalListVectorStoresResponse DeserializeInternalListVectorSt string firstId = default; string lastId = default; bool hasMore = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalListVectorStoresResponseObject(property.Value.GetString()); + @object = new InternalListVectorStoresResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("data"u8)) + if (prop.NameEquals("data"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(VectorStore.DeserializeVectorStore(item, options)); } data = array; continue; } - if (property.NameEquals("first_id"u8)) + if (prop.NameEquals("first_id"u8)) { - firstId = property.Value.GetString(); + firstId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_id"u8)) + if (prop.NameEquals("last_id"u8)) { - lastId = property.Value.GetString(); + lastId = prop.Value.GetString(); continue; } - if (property.NameEquals("has_more"u8)) + if (prop.NameEquals("has_more"u8)) { - hasMore = property.Value.GetBoolean(); + hasMore = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalListVectorStoresResponse( @object, data, firstId, lastId, hasMore, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -161,15 +167,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalListVectorStoresResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalListVectorStoresResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalListVectorStoresResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalListVectorStoresResponse(document.RootElement, options); } default: @@ -179,15 +186,20 @@ InternalListVectorStoresResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalListVectorStoresResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalListVectorStoresResponse internalListVectorStoresResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalListVectorStoresResponse(document.RootElement); + if (internalListVectorStoresResponse == null) + { + return null; + } + return BinaryContent.Create(internalListVectorStoresResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalListVectorStoresResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalListVectorStoresResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalListVectorStoresResponse.cs b/src/Generated/Models/InternalListVectorStoresResponse.cs index 98135e24b..3f2157103 100644 --- a/src/Generated/Models/InternalListVectorStoresResponse.cs +++ b/src/Generated/Models/InternalListVectorStoresResponse.cs @@ -4,44 +4,46 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalListVectorStoresResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalListVectorStoresResponse(IEnumerable data, string firstId, string lastId, bool hasMore) - { - Argument.AssertNotNull(data, nameof(data)); - Argument.AssertNotNull(firstId, nameof(firstId)); - Argument.AssertNotNull(lastId, nameof(lastId)); + private protected IDictionary _additionalBinaryDataProperties; - Data = data.ToList(); + internal InternalListVectorStoresResponse(string firstId, string lastId, bool hasMore) + { + Data = new ChangeTrackingList(); FirstId = firstId; LastId = lastId; HasMore = hasMore; } - internal InternalListVectorStoresResponse(InternalListVectorStoresResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal InternalListVectorStoresResponse(InternalListVectorStoresResponseObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary additionalBinaryDataProperties) { Object = @object; Data = data; FirstId = firstId; LastId = lastId; HasMore = hasMore; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalListVectorStoresResponse() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalListVectorStoresResponseObject Object { get; } = InternalListVectorStoresResponseObject.List; + public InternalListVectorStoresResponseObject Object { get; } = "list"; public IReadOnlyList Data { get; } + public string FirstId { get; } + public string LastId { get; } + public bool HasMore { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalListVectorStoresResponseObject.cs b/src/Generated/Models/InternalListVectorStoresResponseObject.cs index 1f3c8a3f2..cf2c64190 100644 --- a/src/Generated/Models/InternalListVectorStoresResponseObject.cs +++ b/src/Generated/Models/InternalListVectorStoresResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalListVectorStoresResponseObject : IEquatable { private readonly string _value; + private const string ListValue = "list"; public InternalListVectorStoresResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ListValue = "list"; + _value = value; + } public static InternalListVectorStoresResponseObject List { get; } = new InternalListVectorStoresResponseObject(ListValue); + public static bool operator ==(InternalListVectorStoresResponseObject left, InternalListVectorStoresResponseObject right) => left.Equals(right); + public static bool operator !=(InternalListVectorStoresResponseObject left, InternalListVectorStoresResponseObject right) => !left.Equals(right); + public static implicit operator InternalListVectorStoresResponseObject(string value) => new InternalListVectorStoresResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalListVectorStoresResponseObject other && Equals(other); + public bool Equals(InternalListVectorStoresResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentImageFileObjectImageFileDetail.cs b/src/Generated/Models/InternalMessageContentImageFileObjectImageFileDetail.cs index c6099b4c4..178be85d1 100644 --- a/src/Generated/Models/InternalMessageContentImageFileObjectImageFileDetail.cs +++ b/src/Generated/Models/InternalMessageContentImageFileObjectImageFileDetail.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentImageFileObjectImageFileDetail : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; public InternalMessageContentImageFileObjectImageFileDetail(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LowValue = "low"; - private const string HighValue = "high"; + _value = value; + } public static InternalMessageContentImageFileObjectImageFileDetail Auto { get; } = new InternalMessageContentImageFileObjectImageFileDetail(AutoValue); + public static InternalMessageContentImageFileObjectImageFileDetail Low { get; } = new InternalMessageContentImageFileObjectImageFileDetail(LowValue); + public static InternalMessageContentImageFileObjectImageFileDetail High { get; } = new InternalMessageContentImageFileObjectImageFileDetail(HighValue); + public static bool operator ==(InternalMessageContentImageFileObjectImageFileDetail left, InternalMessageContentImageFileObjectImageFileDetail right) => left.Equals(right); + public static bool operator !=(InternalMessageContentImageFileObjectImageFileDetail left, InternalMessageContentImageFileObjectImageFileDetail right) => !left.Equals(right); + public static implicit operator InternalMessageContentImageFileObjectImageFileDetail(string value) => new InternalMessageContentImageFileObjectImageFileDetail(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentImageFileObjectImageFileDetail other && Equals(other); + public bool Equals(InternalMessageContentImageFileObjectImageFileDetail other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentImageFileObjectType.cs b/src/Generated/Models/InternalMessageContentImageFileObjectType.cs index 716165ec3..7a34d366e 100644 --- a/src/Generated/Models/InternalMessageContentImageFileObjectType.cs +++ b/src/Generated/Models/InternalMessageContentImageFileObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentImageFileObjectType : IEquatable { private readonly string _value; + private const string ImageFileValue = "image_file"; public InternalMessageContentImageFileObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ImageFileValue = "image_file"; + _value = value; + } public static InternalMessageContentImageFileObjectType ImageFile { get; } = new InternalMessageContentImageFileObjectType(ImageFileValue); + public static bool operator ==(InternalMessageContentImageFileObjectType left, InternalMessageContentImageFileObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageContentImageFileObjectType left, InternalMessageContentImageFileObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageContentImageFileObjectType(string value) => new InternalMessageContentImageFileObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentImageFileObjectType other && Equals(other); + public bool Equals(InternalMessageContentImageFileObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.Serialization.cs b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.Serialization.cs index 376726676..f163923b5 100644 --- a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentImageUrlObjectImageUrl : IJsonModel { + internal InternalMessageContentImageUrlObjectImageUrl() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentImageUrlObjectImageUrl)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("url") != true) + if (_additionalBinaryDataProperties?.ContainsKey("url") != true) { writer.WritePropertyName("url"u8); writer.WriteStringValue(Url.AbsoluteUri); } - if (SerializedAdditionalRawData?.ContainsKey("detail") != true && Optional.IsDefined(Detail)) + if (Optional.IsDefined(Detail) && _additionalBinaryDataProperties?.ContainsKey("detail") != true) { writer.WritePropertyName("detail"u8); writer.WriteStringValue(Detail); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWrit #endif } } - writer.WriteEndObject(); } - InternalMessageContentImageUrlObjectImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentImageUrlObjectImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentImageUrlObjectImageUrl JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentImageUrlObjectImageUrl)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentImageUrlObjectImageUrl(document.RootElement, options); } - internal static InternalMessageContentImageUrlObjectImageUrl DeserializeInternalMessageContentImageUrlObjectImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentImageUrlObjectImageUrl DeserializeInternalMessageContentImageUrlObjectImageUrl(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } Uri url = default; string detail = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) + if (prop.NameEquals("url"u8)) { - url = new Uri(property.Value.GetString()); + url = new Uri(prop.Value.GetString()); continue; } - if (property.NameEquals("detail"u8)) + if (prop.NameEquals("detail"u8)) { - detail = property.Value.GetString(); + detail = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageContentImageUrlObjectImageUrl(url, detail, serializedAdditionalRawData); + return new InternalMessageContentImageUrlObjectImageUrl(url, detail, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write } } - InternalMessageContentImageUrlObjectImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentImageUrlObjectImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentImageUrlObjectImageUrl 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentImageUrlObjectImageUrl(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalMessageContentImageUrlObjectImageUrl IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentImageUrlObjectImageUrl FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentImageUrlObjectImageUrl internalMessageContentImageUrlObjectImageUrl) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentImageUrlObjectImageUrl(document.RootElement); + if (internalMessageContentImageUrlObjectImageUrl == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentImageUrlObjectImageUrl, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentImageUrlObjectImageUrl(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentImageUrlObjectImageUrl(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.cs b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.cs index ec3f49b7f..60e449f28 100644 --- a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.cs +++ b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrl.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentImageUrlObjectImageUrl { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalMessageContentImageUrlObjectImageUrl(Uri url) { Argument.AssertNotNull(url, nameof(url)); @@ -17,17 +19,19 @@ public InternalMessageContentImageUrlObjectImageUrl(Uri url) Url = url; } - internal InternalMessageContentImageUrlObjectImageUrl(Uri url, string detail, IDictionary serializedAdditionalRawData) + internal InternalMessageContentImageUrlObjectImageUrl(Uri url, string detail, IDictionary additionalBinaryDataProperties) { Url = url; Detail = detail; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalMessageContentImageUrlObjectImageUrl() + public Uri Url { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public Uri Url { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrlDetail.cs b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrlDetail.cs index 1ae9181d0..b33325652 100644 --- a/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrlDetail.cs +++ b/src/Generated/Models/InternalMessageContentImageUrlObjectImageUrlDetail.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentImageUrlObjectImageUrlDetail : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; public InternalMessageContentImageUrlObjectImageUrlDetail(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LowValue = "low"; - private const string HighValue = "high"; + _value = value; + } public static InternalMessageContentImageUrlObjectImageUrlDetail Auto { get; } = new InternalMessageContentImageUrlObjectImageUrlDetail(AutoValue); + public static InternalMessageContentImageUrlObjectImageUrlDetail Low { get; } = new InternalMessageContentImageUrlObjectImageUrlDetail(LowValue); + public static InternalMessageContentImageUrlObjectImageUrlDetail High { get; } = new InternalMessageContentImageUrlObjectImageUrlDetail(HighValue); + public static bool operator ==(InternalMessageContentImageUrlObjectImageUrlDetail left, InternalMessageContentImageUrlObjectImageUrlDetail right) => left.Equals(right); + public static bool operator !=(InternalMessageContentImageUrlObjectImageUrlDetail left, InternalMessageContentImageUrlObjectImageUrlDetail right) => !left.Equals(right); + public static implicit operator InternalMessageContentImageUrlObjectImageUrlDetail(string value) => new InternalMessageContentImageUrlObjectImageUrlDetail(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentImageUrlObjectImageUrlDetail other && Equals(other); + public bool Equals(InternalMessageContentImageUrlObjectImageUrlDetail other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentImageUrlObjectType.cs b/src/Generated/Models/InternalMessageContentImageUrlObjectType.cs index 741398764..50e542907 100644 --- a/src/Generated/Models/InternalMessageContentImageUrlObjectType.cs +++ b/src/Generated/Models/InternalMessageContentImageUrlObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentImageUrlObjectType : IEquatable { private readonly string _value; + private const string ImageUrlValue = "image_url"; public InternalMessageContentImageUrlObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ImageUrlValue = "image_url"; + _value = value; + } public static InternalMessageContentImageUrlObjectType ImageUrl { get; } = new InternalMessageContentImageUrlObjectType(ImageUrlValue); + public static bool operator ==(InternalMessageContentImageUrlObjectType left, InternalMessageContentImageUrlObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageContentImageUrlObjectType left, InternalMessageContentImageUrlObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageContentImageUrlObjectType(string value) => new InternalMessageContentImageUrlObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentImageUrlObjectType other && Equals(other); + public bool Equals(InternalMessageContentImageUrlObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.Serialization.cs b/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.Serialization.cs index a05a67384..e1675137f 100644 --- a/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentItemFileObjectImageFile : IJsonModel { + internal InternalMessageContentItemFileObjectImageFile() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentItemFileObjectImageFile)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("detail") != true && Optional.IsDefined(Detail)) + if (Optional.IsDefined(Detail) && _additionalBinaryDataProperties?.ContainsKey("detail") != true) { writer.WritePropertyName("detail"u8); writer.WriteStringValue(Detail); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWri #endif } } - writer.WriteEndObject(); } - InternalMessageContentItemFileObjectImageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentItemFileObjectImageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentItemFileObjectImageFile JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentItemFileObjectImageFile)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentItemFileObjectImageFile(document.RootElement, options); } - internal static InternalMessageContentItemFileObjectImageFile DeserializeInternalMessageContentItemFileObjectImageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentItemFileObjectImageFile DeserializeInternalMessageContentItemFileObjectImageFile(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; string detail = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("detail"u8)) + if (prop.NameEquals("detail"u8)) { - detail = property.Value.GetString(); + detail = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageContentItemFileObjectImageFile(fileId, detail, serializedAdditionalRawData); + return new InternalMessageContentItemFileObjectImageFile(fileId, detail, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Writ } } - InternalMessageContentItemFileObjectImageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentItemFileObjectImageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentItemFileObjectImageFile 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentItemFileObjectImageFile(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalMessageContentItemFileObjectImageFile IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentItemFileObjectImageFile FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentItemFileObjectImageFile internalMessageContentItemFileObjectImageFile) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentItemFileObjectImageFile(document.RootElement); + if (internalMessageContentItemFileObjectImageFile == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentItemFileObjectImageFile, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentItemFileObjectImageFile(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentItemFileObjectImageFile(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.cs b/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.cs index b002cac9f..9b896a1e1 100644 --- a/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.cs +++ b/src/Generated/Models/InternalMessageContentItemFileObjectImageFile.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentItemFileObjectImageFile { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalMessageContentItemFileObjectImageFile(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -17,17 +19,19 @@ public InternalMessageContentItemFileObjectImageFile(string fileId) FileId = fileId; } - internal InternalMessageContentItemFileObjectImageFile(string fileId, string detail, IDictionary serializedAdditionalRawData) + internal InternalMessageContentItemFileObjectImageFile(string fileId, string detail, IDictionary additionalBinaryDataProperties) { FileId = fileId; Detail = detail; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalMessageContentItemFileObjectImageFile() + public string FileId { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentRefusalObjectType.cs b/src/Generated/Models/InternalMessageContentRefusalObjectType.cs index 7a127f292..bf9339d90 100644 --- a/src/Generated/Models/InternalMessageContentRefusalObjectType.cs +++ b/src/Generated/Models/InternalMessageContentRefusalObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentRefusalObjectType : IEquatable { private readonly string _value; + private const string RefusalValue = "refusal"; public InternalMessageContentRefusalObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string RefusalValue = "refusal"; + _value = value; + } public static InternalMessageContentRefusalObjectType Refusal { get; } = new InternalMessageContentRefusalObjectType(RefusalValue); + public static bool operator ==(InternalMessageContentRefusalObjectType left, InternalMessageContentRefusalObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageContentRefusalObjectType left, InternalMessageContentRefusalObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageContentRefusalObjectType(string value) => new InternalMessageContentRefusalObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentRefusalObjectType other && Equals(other); + public bool Equals(InternalMessageContentRefusalObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.Serialization.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.Serialization.cs index a2d9393c1..9566b3a42 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.Serialization.cs @@ -7,141 +7,124 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFileCitationObject : IJsonModel { + internal InternalMessageContentTextAnnotationsFileCitationObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextAnnotationsFileCitationObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("file_citation") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_citation") != true) { writer.WritePropertyName("file_citation"u8); writer.WriteObjectValue(FileCitation, options); } - if (SerializedAdditionalRawData?.ContainsKey("start_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("start_index") != true) { writer.WritePropertyName("start_index"u8); writer.WriteNumberValue(StartIndex); } - if (SerializedAdditionalRawData?.ContainsKey("end_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("end_index") != true) { writer.WritePropertyName("end_index"u8); writer.WriteNumberValue(EndIndex); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageContentTextAnnotationsFileCitationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextAnnotationsFileCitationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageContentTextAnnotationsFileCitationObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageContentTextObjectAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextAnnotationsFileCitationObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextAnnotationsFileCitationObject(document.RootElement, options); } - internal static InternalMessageContentTextAnnotationsFileCitationObject DeserializeInternalMessageContentTextAnnotationsFileCitationObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextAnnotationsFileCitationObject DeserializeInternalMessageContentTextAnnotationsFileCitationObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_citation"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string text = default; InternalMessageContentTextAnnotationsFileCitationObjectFileCitation fileCitation = default; int startIndex = default; int endIndex = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text"u8)) + if (prop.NameEquals("type"u8)) { - text = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("file_citation"u8)) + if (prop.NameEquals("text"u8)) { - fileCitation = InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(property.Value, options); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) + if (prop.NameEquals("file_citation"u8)) { - startIndex = property.Value.GetInt32(); + fileCitation = InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(prop.Value, options); continue; } - if (property.NameEquals("end_index"u8)) + if (prop.NameEquals("start_index"u8)) { - endIndex = property.Value.GetInt32(); + startIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("end_index"u8)) { - type = property.Value.GetString(); + endIndex = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalMessageContentTextAnnotationsFileCitationObject( - type, - serializedAdditionalRawData, + @type, + additionalBinaryDataProperties, text, fileCitation, startIndex, endIndex); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +134,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextAnnotationsFileCitationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageContentTextAnnotationsFileCitationObject)PersistableModelCreateCore(data, options); + protected override InternalMessageContentTextObjectAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextAnnotationsFileCitationObject(document.RootElement, options); } default: @@ -169,15 +153,20 @@ InternalMessageContentTextAnnotationsFileCitationObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageContentTextAnnotationsFileCitationObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextAnnotationsFileCitationObject internalMessageContentTextAnnotationsFileCitationObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextAnnotationsFileCitationObject(document.RootElement); + if (internalMessageContentTextAnnotationsFileCitationObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextAnnotationsFileCitationObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextAnnotationsFileCitationObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextAnnotationsFileCitationObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.cs index f1a6d8ea9..e5a797c9e 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObject.cs @@ -4,24 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFileCitationObject : InternalMessageContentTextObjectAnnotation { - public InternalMessageContentTextAnnotationsFileCitationObject(string text, InternalMessageContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int startIndex, int endIndex) + public InternalMessageContentTextAnnotationsFileCitationObject(string text, InternalMessageContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int startIndex, int endIndex) : base("file_citation") { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(fileCitation, nameof(fileCitation)); - Type = "file_citation"; Text = text; FileCitation = fileCitation; StartIndex = startIndex; EndIndex = endIndex; } - internal InternalMessageContentTextAnnotationsFileCitationObject(string type, IDictionary serializedAdditionalRawData, string text, InternalMessageContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int startIndex, int endIndex) : base(type, serializedAdditionalRawData) + internal InternalMessageContentTextAnnotationsFileCitationObject(string @type, IDictionary additionalBinaryDataProperties, string text, InternalMessageContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int startIndex, int endIndex) : base(@type, additionalBinaryDataProperties) { Text = text; FileCitation = fileCitation; @@ -29,13 +29,12 @@ internal InternalMessageContentTextAnnotationsFileCitationObject(string type, ID EndIndex = endIndex; } - internal InternalMessageContentTextAnnotationsFileCitationObject() - { - } - public string Text { get; set; } + public InternalMessageContentTextAnnotationsFileCitationObjectFileCitation FileCitation { get; set; } + public int StartIndex { get; set; } + public int EndIndex { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs index b18974701..4e5168aad 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFileCitationObjectFileCitation : IJsonModel { + internal InternalMessageContentTextAnnotationsFileCitationObjectFileCitation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextAnnotationsFileCitationObjectFileCitation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextAnnotationsFileCitationObjectFileCitation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentTextAnnotationsFileCitationObjectFileCitation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextAnnotationsFileCitationObjectFileCitation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, options); } - internal static InternalMessageContentTextAnnotationsFileCitationObjectFileCitation DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextAnnotationsFileCitationObjectFileCitation DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(fileId, serializedAdditionalRawData); + return new InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(fileId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextAnnotationsFileCitationObjectFileCitation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentTextAnnotationsFileCitationObjectFileCitation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalMessageContentTextAnnotationsFileCitationObjectFileCitation IPersistable string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentTextAnnotationsFileCitationObjectFileCitation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextAnnotationsFileCitationObjectFileCitation internalMessageContentTextAnnotationsFileCitationObjectFileCitation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement); + if (internalMessageContentTextAnnotationsFileCitationObjectFileCitation == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextAnnotationsFileCitationObjectFileCitation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.cs index 1c255cb2c..2fc0281be 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFileCitationObjectFileCitation.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFileCitationObjectFileCitation { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -17,16 +19,18 @@ public InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(strin FileId = fileId; } - internal InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(string fileId, IDictionary serializedAdditionalRawData) + internal InternalMessageContentTextAnnotationsFileCitationObjectFileCitation(string fileId, IDictionary additionalBinaryDataProperties) { FileId = fileId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalMessageContentTextAnnotationsFileCitationObjectFileCitation() + public string FileId { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.Serialization.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.Serialization.cs index c06a4f2d7..ad60be6dd 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.Serialization.cs @@ -7,141 +7,124 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFilePathObject : IJsonModel { + internal InternalMessageContentTextAnnotationsFilePathObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextAnnotationsFilePathObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("file_path") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_path") != true) { writer.WritePropertyName("file_path"u8); writer.WriteObjectValue(FilePath, options); } - if (SerializedAdditionalRawData?.ContainsKey("start_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("start_index") != true) { writer.WritePropertyName("start_index"u8); writer.WriteNumberValue(StartIndex); } - if (SerializedAdditionalRawData?.ContainsKey("end_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("end_index") != true) { writer.WritePropertyName("end_index"u8); writer.WriteNumberValue(EndIndex); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageContentTextAnnotationsFilePathObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextAnnotationsFilePathObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageContentTextAnnotationsFilePathObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageContentTextObjectAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextAnnotationsFilePathObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextAnnotationsFilePathObject(document.RootElement, options); } - internal static InternalMessageContentTextAnnotationsFilePathObject DeserializeInternalMessageContentTextAnnotationsFilePathObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextAnnotationsFilePathObject DeserializeInternalMessageContentTextAnnotationsFilePathObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_path"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string text = default; InternalMessageContentTextAnnotationsFilePathObjectFilePath filePath = default; int startIndex = default; int endIndex = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("text"u8)) + if (prop.NameEquals("type"u8)) { - text = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("file_path"u8)) + if (prop.NameEquals("text"u8)) { - filePath = InternalMessageContentTextAnnotationsFilePathObjectFilePath.DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(property.Value, options); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) + if (prop.NameEquals("file_path"u8)) { - startIndex = property.Value.GetInt32(); + filePath = InternalMessageContentTextAnnotationsFilePathObjectFilePath.DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(prop.Value, options); continue; } - if (property.NameEquals("end_index"u8)) + if (prop.NameEquals("start_index"u8)) { - endIndex = property.Value.GetInt32(); + startIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("end_index"u8)) { - type = property.Value.GetString(); + endIndex = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalMessageContentTextAnnotationsFilePathObject( - type, - serializedAdditionalRawData, + @type, + additionalBinaryDataProperties, text, filePath, startIndex, endIndex); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +134,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextAnnotationsFilePathObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageContentTextAnnotationsFilePathObject)PersistableModelCreateCore(data, options); + protected override InternalMessageContentTextObjectAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextAnnotationsFilePathObject(document.RootElement, options); } default: @@ -169,15 +153,20 @@ InternalMessageContentTextAnnotationsFilePathObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageContentTextAnnotationsFilePathObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextAnnotationsFilePathObject internalMessageContentTextAnnotationsFilePathObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextAnnotationsFilePathObject(document.RootElement); + if (internalMessageContentTextAnnotationsFilePathObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextAnnotationsFilePathObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextAnnotationsFilePathObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextAnnotationsFilePathObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.cs index c0098007c..c6f617972 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObject.cs @@ -4,24 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFilePathObject : InternalMessageContentTextObjectAnnotation { - public InternalMessageContentTextAnnotationsFilePathObject(string text, InternalMessageContentTextAnnotationsFilePathObjectFilePath filePath, int startIndex, int endIndex) + public InternalMessageContentTextAnnotationsFilePathObject(string text, InternalMessageContentTextAnnotationsFilePathObjectFilePath filePath, int startIndex, int endIndex) : base("file_path") { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(filePath, nameof(filePath)); - Type = "file_path"; Text = text; FilePath = filePath; StartIndex = startIndex; EndIndex = endIndex; } - internal InternalMessageContentTextAnnotationsFilePathObject(string type, IDictionary serializedAdditionalRawData, string text, InternalMessageContentTextAnnotationsFilePathObjectFilePath filePath, int startIndex, int endIndex) : base(type, serializedAdditionalRawData) + internal InternalMessageContentTextAnnotationsFilePathObject(string @type, IDictionary additionalBinaryDataProperties, string text, InternalMessageContentTextAnnotationsFilePathObjectFilePath filePath, int startIndex, int endIndex) : base(@type, additionalBinaryDataProperties) { Text = text; FilePath = filePath; @@ -29,13 +29,12 @@ internal InternalMessageContentTextAnnotationsFilePathObject(string type, IDicti EndIndex = endIndex; } - internal InternalMessageContentTextAnnotationsFilePathObject() - { - } - public string Text { get; set; } + public InternalMessageContentTextAnnotationsFilePathObjectFilePath FilePath { get; set; } + public int StartIndex { get; set; } + public int EndIndex { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.Serialization.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.Serialization.cs index e398f1480..9c2063bd9 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFilePathObjectFilePath : IJsonModel { + internal InternalMessageContentTextAnnotationsFilePathObjectFilePath() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextAnnotationsFilePathObjectFilePath)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Wri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Wri #endif } } - writer.WriteEndObject(); } - InternalMessageContentTextAnnotationsFilePathObjectFilePath IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextAnnotationsFilePathObjectFilePath IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentTextAnnotationsFilePathObjectFilePath JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextAnnotationsFilePathObjectFilePath)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(document.RootElement, options); } - internal static InternalMessageContentTextAnnotationsFilePathObjectFilePath DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextAnnotationsFilePathObjectFilePath DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageContentTextAnnotationsFilePathObjectFilePath(fileId, serializedAdditionalRawData); + return new InternalMessageContentTextAnnotationsFilePathObjectFilePath(fileId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextAnnotationsFilePathObjectFilePath IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentTextAnnotationsFilePathObjectFilePath 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalMessageContentTextAnnotationsFilePathObjectFilePath IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentTextAnnotationsFilePathObjectFilePath FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextAnnotationsFilePathObjectFilePath internalMessageContentTextAnnotationsFilePathObjectFilePath) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(document.RootElement); + if (internalMessageContentTextAnnotationsFilePathObjectFilePath == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextAnnotationsFilePathObjectFilePath, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextAnnotationsFilePathObjectFilePath(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextAnnotationsFilePathObjectFilePath(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.cs b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.cs index de47c05b1..048c7f9e1 100644 --- a/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.cs +++ b/src/Generated/Models/InternalMessageContentTextAnnotationsFilePathObjectFilePath.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextAnnotationsFilePathObjectFilePath { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalMessageContentTextAnnotationsFilePathObjectFilePath(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -17,16 +19,18 @@ public InternalMessageContentTextAnnotationsFilePathObjectFilePath(string fileId FileId = fileId; } - internal InternalMessageContentTextAnnotationsFilePathObjectFilePath(string fileId, IDictionary serializedAdditionalRawData) + internal InternalMessageContentTextAnnotationsFilePathObjectFilePath(string fileId, IDictionary additionalBinaryDataProperties) { FileId = fileId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalMessageContentTextAnnotationsFilePathObjectFilePath() + public string FileId { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; set; } } } diff --git a/src/Generated/Models/InternalMessageContentTextObjectAnnotation.Serialization.cs b/src/Generated/Models/InternalMessageContentTextObjectAnnotation.Serialization.cs index 92f8d5b79..d2fab5507 100644 --- a/src/Generated/Models/InternalMessageContentTextObjectAnnotation.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextObjectAnnotation.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownMessageContentTextObjectAnnotation))] - internal partial class InternalMessageContentTextObjectAnnotation : IJsonModel + internal abstract partial class InternalMessageContentTextObjectAnnotation : IJsonModel { + internal InternalMessageContentTextObjectAnnotation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextObjectAnnotation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalMessageContentTextObjectAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextObjectAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentTextObjectAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextObjectAnnotation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement, options); } - internal static InternalMessageContentTextObjectAnnotation DeserializeInternalMessageContentTextObjectAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextObjectAnnotation DeserializeInternalMessageContentTextObjectAnnotation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "file_citation": return InternalMessageContentTextAnnotationsFileCitationObject.DeserializeInternalMessageContentTextAnnotationsFileCitationObject(element, options); - case "file_path": return InternalMessageContentTextAnnotationsFilePathObject.DeserializeInternalMessageContentTextAnnotationsFilePathObject(element, options); + case "file_citation": + return InternalMessageContentTextAnnotationsFileCitationObject.DeserializeInternalMessageContentTextAnnotationsFileCitationObject(element, options); + case "file_path": + return InternalMessageContentTextAnnotationsFilePathObject.DeserializeInternalMessageContentTextAnnotationsFilePathObject(element, options); } } return UnknownMessageContentTextObjectAnnotation.DeserializeUnknownMessageContentTextObjectAnnotation(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(M } } - InternalMessageContentTextObjectAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextObjectAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentTextObjectAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement, options); } default: @@ -110,15 +122,20 @@ InternalMessageContentTextObjectAnnotation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentTextObjectAnnotation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextObjectAnnotation internalMessageContentTextObjectAnnotation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement); + if (internalMessageContentTextObjectAnnotation == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextObjectAnnotation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextObjectAnnotation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextObjectAnnotation.cs b/src/Generated/Models/InternalMessageContentTextObjectAnnotation.cs index 4e2df613a..443e712f4 100644 --- a/src/Generated/Models/InternalMessageContentTextObjectAnnotation.cs +++ b/src/Generated/Models/InternalMessageContentTextObjectAnnotation.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal abstract partial class InternalMessageContentTextObjectAnnotation { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalMessageContentTextObjectAnnotation() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalMessageContentTextObjectAnnotation(string @type) { + Type = @type; } - internal InternalMessageContentTextObjectAnnotation(string type, IDictionary serializedAdditionalRawData) + internal InternalMessageContentTextObjectAnnotation(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageContentTextObjectText.Serialization.cs b/src/Generated/Models/InternalMessageContentTextObjectText.Serialization.cs index 0c951aee1..e023a7c53 100644 --- a/src/Generated/Models/InternalMessageContentTextObjectText.Serialization.cs +++ b/src/Generated/Models/InternalMessageContentTextObjectText.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextObjectText : IJsonModel { + internal InternalMessageContentTextObjectText() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextObjectText)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("value") != true) + if (_additionalBinaryDataProperties?.ContainsKey("value") != true) { writer.WritePropertyName("value"u8); writer.WriteStringValue(Value); } - if (SerializedAdditionalRawData?.ContainsKey("annotations") != true) + if (_additionalBinaryDataProperties?.ContainsKey("annotations") != true) { writer.WritePropertyName("annotations"u8); writer.WriteStartArray(); - foreach (var item in Annotations) + foreach (InternalMessageContentTextObjectAnnotation item in Annotations) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter write } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,44 +65,41 @@ void IJsonModel.Write(Utf8JsonWriter write #endif } } - writer.WriteEndObject(); } - InternalMessageContentTextObjectText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextObjectText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageContentTextObjectText JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextObjectText)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextObjectText(document.RootElement, options); } - internal static InternalMessageContentTextObjectText DeserializeInternalMessageContentTextObjectText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageContentTextObjectText DeserializeInternalMessageContentTextObjectText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string value = default; IList annotations = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("value"u8)) + if (prop.NameEquals("value"u8)) { - value = property.Value.GetString(); + value = prop.Value.GetString(); continue; } - if (property.NameEquals("annotations"u8)) + if (prop.NameEquals("annotations"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalMessageContentTextObjectAnnotation.DeserializeInternalMessageContentTextObjectAnnotation(item, options)); } @@ -101,18 +108,17 @@ internal static InternalMessageContentTextObjectText DeserializeInternalMessageC } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageContentTextObjectText(value, annotations, serializedAdditionalRawData); + return new InternalMessageContentTextObjectText(value, annotations, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -122,15 +128,16 @@ BinaryData IPersistableModel.Write(ModelRe } } - InternalMessageContentTextObjectText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextObjectText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageContentTextObjectText 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextObjectText(document.RootElement, options); } default: @@ -140,15 +147,20 @@ InternalMessageContentTextObjectText IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageContentTextObjectText FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageContentTextObjectText internalMessageContentTextObjectText) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageContentTextObjectText(document.RootElement); + if (internalMessageContentTextObjectText == null) + { + return null; + } + return BinaryContent.Create(internalMessageContentTextObjectText, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageContentTextObjectText(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageContentTextObjectText(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageContentTextObjectText.cs b/src/Generated/Models/InternalMessageContentTextObjectText.cs index 3ebc901f8..61cfcfb00 100644 --- a/src/Generated/Models/InternalMessageContentTextObjectText.cs +++ b/src/Generated/Models/InternalMessageContentTextObjectText.cs @@ -5,12 +5,14 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageContentTextObjectText { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalMessageContentTextObjectText(string value, IEnumerable annotations) { Argument.AssertNotNull(value, nameof(value)); @@ -20,18 +22,21 @@ public InternalMessageContentTextObjectText(string value, IEnumerable annotations, IDictionary serializedAdditionalRawData) + internal InternalMessageContentTextObjectText(string value, IList annotations, IDictionary additionalBinaryDataProperties) { Value = value; Annotations = annotations; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalMessageContentTextObjectText() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Value { get; set; } + public IList Annotations { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageContentTextObjectType.cs b/src/Generated/Models/InternalMessageContentTextObjectType.cs index daf657e15..965bf25b9 100644 --- a/src/Generated/Models/InternalMessageContentTextObjectType.cs +++ b/src/Generated/Models/InternalMessageContentTextObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageContentTextObjectType : IEquatable { private readonly string _value; + private const string TextValue = "text"; public InternalMessageContentTextObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextValue = "text"; + _value = value; + } public static InternalMessageContentTextObjectType Text { get; } = new InternalMessageContentTextObjectType(TextValue); + public static bool operator ==(InternalMessageContentTextObjectType left, InternalMessageContentTextObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageContentTextObjectType left, InternalMessageContentTextObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageContentTextObjectType(string value) => new InternalMessageContentTextObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageContentTextObjectType other && Equals(other); + public bool Equals(InternalMessageContentTextObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs index 7b0d037e3..7ac025e15 100644 --- a/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContent.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownMessageDeltaContent))] - internal partial class InternalMessageDeltaContent : IJsonModel + internal abstract partial class InternalMessageDeltaContent : IJsonModel { + internal InternalMessageDeltaContent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,46 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContent(document.RootElement, options); } - internal static InternalMessageDeltaContent DeserializeInternalMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContent DeserializeInternalMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "image_file": return InternalMessageDeltaContentImageFileObject.DeserializeInternalMessageDeltaContentImageFileObject(element, options); - case "image_url": return InternalMessageDeltaContentImageUrlObject.DeserializeInternalMessageDeltaContentImageUrlObject(element, options); - case "refusal": return InternalMessageDeltaContentRefusalObject.DeserializeInternalMessageDeltaContentRefusalObject(element, options); - case "text": return InternalMessageDeltaContentTextObject.DeserializeInternalMessageDeltaContentTextObject(element, options); + case "image_file": + return InternalMessageDeltaContentImageFileObject.DeserializeInternalMessageDeltaContentImageFileObject(element, options); + case "image_url": + return InternalMessageDeltaContentImageUrlObject.DeserializeInternalMessageDeltaContentImageUrlObject(element, options); + case "text": + return InternalMessageDeltaContentTextObject.DeserializeInternalMessageDeltaContentTextObject(element, options); + case "refusal": + return InternalMessageDeltaContentRefusalObject.DeserializeInternalMessageDeltaContentRefusalObject(element, options); } } return UnknownMessageDeltaContent.DeserializeUnknownMessageDeltaContent(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -94,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalMessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContent(document.RootElement, options); } default: @@ -112,15 +126,20 @@ InternalMessageDeltaContent IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContent internalMessageDeltaContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContent(document.RootElement); + if (internalMessageDeltaContent == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContent, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContent.cs b/src/Generated/Models/InternalMessageDeltaContent.cs index 861574e93..007a832fe 100644 --- a/src/Generated/Models/InternalMessageDeltaContent.cs +++ b/src/Generated/Models/InternalMessageDeltaContent.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal abstract partial class InternalMessageDeltaContent { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalMessageDeltaContent() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalMessageDeltaContent(string @type) { + Type = @type; } - internal InternalMessageDeltaContent(string type, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContent(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageFileObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentImageFileObject.Serialization.cs index 56a49b626..b42753383 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageFileObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageFileObject.Serialization.cs @@ -7,117 +7,100 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageFileObject : IJsonModel { + internal InternalMessageDeltaContentImageFileObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentImageFileObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("image_file") != true && Optional.IsDefined(ImageFile)) + if (Optional.IsDefined(ImageFile) && _additionalBinaryDataProperties?.ContainsKey("image_file") != true) { writer.WritePropertyName("image_file"u8); writer.WriteObjectValue(ImageFile, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentImageFileObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentImageFileObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentImageFileObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentImageFileObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentImageFileObject(document.RootElement, options); } - internal static InternalMessageDeltaContentImageFileObject DeserializeInternalMessageDeltaContentImageFileObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentImageFileObject DeserializeInternalMessageDeltaContentImageFileObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "image_file"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; InternalMessageDeltaContentImageFileObjectImageFile imageFile = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("image_file"u8)) + if (prop.NameEquals("index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - imageFile = InternalMessageDeltaContentImageFileObjectImageFile.DeserializeInternalMessageDeltaContentImageFileObjectImageFile(property.Value, options); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("image_file"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + imageFile = InternalMessageDeltaContentImageFileObjectImageFile.DeserializeInternalMessageDeltaContentImageFileObjectImageFile(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentImageFileObject(type, serializedAdditionalRawData, index, imageFile); + return new InternalMessageDeltaContentImageFileObject(@type, additionalBinaryDataProperties, index, imageFile); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -127,15 +110,16 @@ BinaryData IPersistableModel.Write(M } } - InternalMessageDeltaContentImageFileObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentImageFileObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentImageFileObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentImageFileObject(document.RootElement, options); } default: @@ -145,15 +129,20 @@ InternalMessageDeltaContentImageFileObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentImageFileObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentImageFileObject internalMessageDeltaContentImageFileObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentImageFileObject(document.RootElement); + if (internalMessageDeltaContentImageFileObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentImageFileObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentImageFileObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentImageFileObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageFileObject.cs b/src/Generated/Models/InternalMessageDeltaContentImageFileObject.cs index 09615bdae..8573af8ac 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageFileObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageFileObject.cs @@ -9,23 +9,19 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageFileObject : InternalMessageDeltaContent { - internal InternalMessageDeltaContentImageFileObject(int index) + internal InternalMessageDeltaContentImageFileObject(int index) : base("image_file") { - Type = "image_file"; Index = index; } - internal InternalMessageDeltaContentImageFileObject(string type, IDictionary serializedAdditionalRawData, int index, InternalMessageDeltaContentImageFileObjectImageFile imageFile) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentImageFileObject(string @type, IDictionary additionalBinaryDataProperties, int index, InternalMessageDeltaContentImageFileObjectImageFile imageFile) : base(@type, additionalBinaryDataProperties) { Index = index; ImageFile = imageFile; } - internal InternalMessageDeltaContentImageFileObject() - { - } - public int Index { get; } + public InternalMessageDeltaContentImageFileObjectImageFile ImageFile { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.Serialization.cs index aeba95b5b..38f2a8da1 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalMessageDeltaContentImageFileObjectImageFile : IJs { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentImageFileObjectImageFile)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true && Optional.IsDefined(FileId)) + if (Optional.IsDefined(FileId) && _additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("detail") != true && Optional.IsDefined(Detail)) + if (Optional.IsDefined(Detail) && _additionalBinaryDataProperties?.ContainsKey("detail") != true) { writer.WritePropertyName("detail"u8); writer.WriteStringValue(Detail); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8J } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8J #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaContentImageFileObjectImageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentImageFileObjectImageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContentImageFileObjectImageFile JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentImageFileObjectImageFile)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentImageFileObjectImageFile(document.RootElement, options); } - internal static InternalMessageDeltaContentImageFileObjectImageFile DeserializeInternalMessageDeltaContentImageFileObjectImageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentImageFileObjectImageFile DeserializeInternalMessageDeltaContentImageFileObjectImageFile(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; string detail = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("detail"u8)) + if (prop.NameEquals("detail"u8)) { - detail = property.Value.GetString(); + detail = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentImageFileObjectImageFile(fileId, detail, serializedAdditionalRawData); + return new InternalMessageDeltaContentImageFileObjectImageFile(fileId, detail, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentImageFileObjectImageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContentImageFileObjectImageFile 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentImageFileObjectImageFile(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalMessageDeltaContentImageFileObjectImageFile IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContentImageFileObjectImageFile FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentImageFileObjectImageFile internalMessageDeltaContentImageFileObjectImageFile) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentImageFileObjectImageFile(document.RootElement); + if (internalMessageDeltaContentImageFileObjectImageFile == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentImageFileObjectImageFile, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentImageFileObjectImageFile(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentImageFileObjectImageFile(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.cs b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.cs index ce44aab8c..e550f5c0d 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFile.cs @@ -9,18 +9,25 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageFileObjectImageFile { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaContentImageFileObjectImageFile() { } - internal InternalMessageDeltaContentImageFileObjectImageFile(string fileId, string detail, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContentImageFileObjectImageFile(string fileId, string detail, IDictionary additionalBinaryDataProperties) { FileId = fileId; Detail = detail; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFileDetail.cs b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFileDetail.cs index 3de4b3ed9..08f9beab9 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFileDetail.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageFileObjectImageFileDetail.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageDeltaContentImageFileObjectImageFileDetail : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; public InternalMessageDeltaContentImageFileObjectImageFileDetail(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LowValue = "low"; - private const string HighValue = "high"; + _value = value; + } public static InternalMessageDeltaContentImageFileObjectImageFileDetail Auto { get; } = new InternalMessageDeltaContentImageFileObjectImageFileDetail(AutoValue); + public static InternalMessageDeltaContentImageFileObjectImageFileDetail Low { get; } = new InternalMessageDeltaContentImageFileObjectImageFileDetail(LowValue); + public static InternalMessageDeltaContentImageFileObjectImageFileDetail High { get; } = new InternalMessageDeltaContentImageFileObjectImageFileDetail(HighValue); + public static bool operator ==(InternalMessageDeltaContentImageFileObjectImageFileDetail left, InternalMessageDeltaContentImageFileObjectImageFileDetail right) => left.Equals(right); + public static bool operator !=(InternalMessageDeltaContentImageFileObjectImageFileDetail left, InternalMessageDeltaContentImageFileObjectImageFileDetail right) => !left.Equals(right); + public static implicit operator InternalMessageDeltaContentImageFileObjectImageFileDetail(string value) => new InternalMessageDeltaContentImageFileObjectImageFileDetail(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageDeltaContentImageFileObjectImageFileDetail other && Equals(other); + public bool Equals(InternalMessageDeltaContentImageFileObjectImageFileDetail other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.Serialization.cs index 40317ea42..696a1fe05 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.Serialization.cs @@ -7,117 +7,100 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageUrlObject : IJsonModel { + internal InternalMessageDeltaContentImageUrlObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentImageUrlObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("image_url") != true && Optional.IsDefined(ImageUrl)) + if (Optional.IsDefined(ImageUrl) && _additionalBinaryDataProperties?.ContainsKey("image_url") != true) { writer.WritePropertyName("image_url"u8); writer.WriteObjectValue(ImageUrl, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentImageUrlObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentImageUrlObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentImageUrlObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentImageUrlObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentImageUrlObject(document.RootElement, options); } - internal static InternalMessageDeltaContentImageUrlObject DeserializeInternalMessageDeltaContentImageUrlObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentImageUrlObject DeserializeInternalMessageDeltaContentImageUrlObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "image_url"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; InternalMessageDeltaContentImageUrlObjectImageUrl imageUrl = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("image_url"u8)) + if (prop.NameEquals("index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - imageUrl = InternalMessageDeltaContentImageUrlObjectImageUrl.DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(property.Value, options); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("image_url"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + imageUrl = InternalMessageDeltaContentImageUrlObjectImageUrl.DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentImageUrlObject(type, serializedAdditionalRawData, index, imageUrl); + return new InternalMessageDeltaContentImageUrlObject(@type, additionalBinaryDataProperties, index, imageUrl); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -127,15 +110,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalMessageDeltaContentImageUrlObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentImageUrlObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentImageUrlObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentImageUrlObject(document.RootElement, options); } default: @@ -145,15 +129,20 @@ InternalMessageDeltaContentImageUrlObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentImageUrlObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentImageUrlObject internalMessageDeltaContentImageUrlObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentImageUrlObject(document.RootElement); + if (internalMessageDeltaContentImageUrlObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentImageUrlObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentImageUrlObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentImageUrlObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.cs b/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.cs index 07fa17e8e..8ea63feef 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageUrlObject.cs @@ -9,23 +9,19 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageUrlObject : InternalMessageDeltaContent { - internal InternalMessageDeltaContentImageUrlObject(int index) + internal InternalMessageDeltaContentImageUrlObject(int index) : base("image_url") { - Type = "image_url"; Index = index; } - internal InternalMessageDeltaContentImageUrlObject(string type, IDictionary serializedAdditionalRawData, int index, InternalMessageDeltaContentImageUrlObjectImageUrl imageUrl) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentImageUrlObject(string @type, IDictionary additionalBinaryDataProperties, int index, InternalMessageDeltaContentImageUrlObjectImageUrl imageUrl) : base(@type, additionalBinaryDataProperties) { Index = index; ImageUrl = imageUrl; } - internal InternalMessageDeltaContentImageUrlObject() - { - } - public int Index { get; } + public InternalMessageDeltaContentImageUrlObjectImageUrl ImageUrl { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.Serialization.cs index 17fdc9aaa..84fe846be 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalMessageDeltaContentImageUrlObjectImageUrl : IJson { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentImageUrlObjectImageUrl)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("url") != true && Optional.IsDefined(Url)) + if (Optional.IsDefined(Url) && _additionalBinaryDataProperties?.ContainsKey("url") != true) { writer.WritePropertyName("url"u8); writer.WriteStringValue(Url.AbsoluteUri); } - if (SerializedAdditionalRawData?.ContainsKey("detail") != true && Optional.IsDefined(Detail)) + if (Optional.IsDefined(Detail) && _additionalBinaryDataProperties?.ContainsKey("detail") != true) { writer.WritePropertyName("detail"u8); writer.WriteStringValue(Detail); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8Jso } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,63 +56,59 @@ void IJsonModel.Write(Utf8Jso #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaContentImageUrlObjectImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentImageUrlObjectImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContentImageUrlObjectImageUrl JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentImageUrlObjectImageUrl)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(document.RootElement, options); } - internal static InternalMessageDeltaContentImageUrlObjectImageUrl DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentImageUrlObjectImageUrl DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } Uri url = default; string detail = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) + if (prop.NameEquals("url"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - url = new Uri(property.Value.GetString()); + url = new Uri(prop.Value.GetString()); continue; } - if (property.NameEquals("detail"u8)) + if (prop.NameEquals("detail"u8)) { - detail = property.Value.GetString(); + detail = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentImageUrlObjectImageUrl(url, detail, serializedAdditionalRawData); + return new InternalMessageDeltaContentImageUrlObjectImageUrl(url, detail, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -116,15 +118,16 @@ BinaryData IPersistableModel. } } - InternalMessageDeltaContentImageUrlObjectImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentImageUrlObjectImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContentImageUrlObjectImageUrl 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(document.RootElement, options); } default: @@ -134,15 +137,20 @@ InternalMessageDeltaContentImageUrlObjectImageUrl IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContentImageUrlObjectImageUrl FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentImageUrlObjectImageUrl internalMessageDeltaContentImageUrlObjectImageUrl) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(document.RootElement); + if (internalMessageDeltaContentImageUrlObjectImageUrl == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentImageUrlObjectImageUrl, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentImageUrlObjectImageUrl(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentImageUrlObjectImageUrl(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.cs b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.cs index 886c78999..2dc688dee 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrl.cs @@ -9,18 +9,25 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentImageUrlObjectImageUrl { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaContentImageUrlObjectImageUrl() { } - internal InternalMessageDeltaContentImageUrlObjectImageUrl(Uri url, string detail, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContentImageUrlObjectImageUrl(Uri url, string detail, IDictionary additionalBinaryDataProperties) { Url = url; Detail = detail; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public Uri Url { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrlDetail.cs b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrlDetail.cs index ffd7b7bb4..c206463fe 100644 --- a/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrlDetail.cs +++ b/src/Generated/Models/InternalMessageDeltaContentImageUrlObjectImageUrlDetail.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageDeltaContentImageUrlObjectImageUrlDetail : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; public InternalMessageDeltaContentImageUrlObjectImageUrlDetail(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LowValue = "low"; - private const string HighValue = "high"; + _value = value; + } public static InternalMessageDeltaContentImageUrlObjectImageUrlDetail Auto { get; } = new InternalMessageDeltaContentImageUrlObjectImageUrlDetail(AutoValue); + public static InternalMessageDeltaContentImageUrlObjectImageUrlDetail Low { get; } = new InternalMessageDeltaContentImageUrlObjectImageUrlDetail(LowValue); + public static InternalMessageDeltaContentImageUrlObjectImageUrlDetail High { get; } = new InternalMessageDeltaContentImageUrlObjectImageUrlDetail(HighValue); + public static bool operator ==(InternalMessageDeltaContentImageUrlObjectImageUrlDetail left, InternalMessageDeltaContentImageUrlObjectImageUrlDetail right) => left.Equals(right); + public static bool operator !=(InternalMessageDeltaContentImageUrlObjectImageUrlDetail left, InternalMessageDeltaContentImageUrlObjectImageUrlDetail right) => !left.Equals(right); + public static implicit operator InternalMessageDeltaContentImageUrlObjectImageUrlDetail(string value) => new InternalMessageDeltaContentImageUrlObjectImageUrlDetail(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageDeltaContentImageUrlObjectImageUrlDetail other && Equals(other); + public bool Equals(InternalMessageDeltaContentImageUrlObjectImageUrlDetail other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs index 1668fc35c..4e1a14815 100644 --- a/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentRefusalObject.Serialization.cs @@ -7,113 +7,96 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentRefusalObject : IJsonModel { + internal InternalMessageDeltaContentRefusalObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentRefusalObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("refusal") != true && Optional.IsDefined(Refusal)) + if (Optional.IsDefined(Refusal) && _additionalBinaryDataProperties?.ContainsKey("refusal") != true) { writer.WritePropertyName("refusal"u8); writer.WriteStringValue(Refusal); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentRefusalObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentRefusalObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentRefusalObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentRefusalObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement, options); } - internal static InternalMessageDeltaContentRefusalObject DeserializeInternalMessageDeltaContentRefusalObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentRefusalObject DeserializeInternalMessageDeltaContentRefusalObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "refusal"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string refusal = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("index"u8)) { - refusal = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("refusal"u8)) { - type = property.Value.GetString(); + refusal = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentRefusalObject(type, serializedAdditionalRawData, index, refusal); + return new InternalMessageDeltaContentRefusalObject(@type, additionalBinaryDataProperties, index, refusal); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +106,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalMessageDeltaContentRefusalObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentRefusalObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentRefusalObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement, options); } default: @@ -141,15 +125,20 @@ InternalMessageDeltaContentRefusalObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentRefusalObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentRefusalObject internalMessageDeltaContentRefusalObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement); + if (internalMessageDeltaContentRefusalObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentRefusalObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentRefusalObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentRefusalObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs b/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs index d7b88a830..5c7fce448 100644 --- a/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentRefusalObject.cs @@ -9,23 +9,19 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentRefusalObject : InternalMessageDeltaContent { - internal InternalMessageDeltaContentRefusalObject(int index) + internal InternalMessageDeltaContentRefusalObject(int index) : base("refusal") { - Type = "refusal"; Index = index; } - internal InternalMessageDeltaContentRefusalObject(string type, IDictionary serializedAdditionalRawData, int index, string refusal) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentRefusalObject(string @type, IDictionary additionalBinaryDataProperties, int index, string refusal) : base(@type, additionalBinaryDataProperties) { Index = index; Refusal = refusal; } - internal InternalMessageDeltaContentRefusalObject() - { - } - public int Index { get; } + public string Refusal { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.Serialization.cs index f35ad0979..fc6c22d7f 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.Serialization.cs @@ -7,154 +7,136 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFileCitationObject : IJsonModel { + internal InternalMessageDeltaContentTextAnnotationsFileCitationObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextAnnotationsFileCitationObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true && Optional.IsDefined(Text)) + if (Optional.IsDefined(Text) && _additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("file_citation") != true && Optional.IsDefined(FileCitation)) + if (Optional.IsDefined(FileCitation) && _additionalBinaryDataProperties?.ContainsKey("file_citation") != true) { writer.WritePropertyName("file_citation"u8); writer.WriteObjectValue(FileCitation, options); } - if (SerializedAdditionalRawData?.ContainsKey("start_index") != true && Optional.IsDefined(StartIndex)) + if (Optional.IsDefined(StartIndex) && _additionalBinaryDataProperties?.ContainsKey("start_index") != true) { writer.WritePropertyName("start_index"u8); writer.WriteNumberValue(StartIndex.Value); } - if (SerializedAdditionalRawData?.ContainsKey("end_index") != true && Optional.IsDefined(EndIndex)) + if (Optional.IsDefined(EndIndex) && _additionalBinaryDataProperties?.ContainsKey("end_index") != true) { writer.WritePropertyName("end_index"u8); writer.WriteNumberValue(EndIndex.Value); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentTextAnnotationsFileCitationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextAnnotationsFileCitationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextAnnotationsFileCitationObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaTextContentAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextAnnotationsFileCitationObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(document.RootElement, options); } - internal static InternalMessageDeltaContentTextAnnotationsFileCitationObject DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextAnnotationsFileCitationObject DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_citation"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string text = default; InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation fileCitation = default; int? startIndex = default; int? endIndex = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("index"u8)) { - text = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("file_citation"u8)) + if (prop.NameEquals("text"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fileCitation = InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(property.Value, options); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) + if (prop.NameEquals("file_citation"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - startIndex = property.Value.GetInt32(); + fileCitation = InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(prop.Value, options); continue; } - if (property.NameEquals("end_index"u8)) + if (prop.NameEquals("start_index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - endIndex = property.Value.GetInt32(); + startIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("end_index"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalMessageDeltaContentTextAnnotationsFileCitationObject( - type, - serializedAdditionalRawData, + @type, + additionalBinaryDataProperties, index, text, fileCitation, @@ -162,10 +144,11 @@ internal static InternalMessageDeltaContentTextAnnotationsFileCitationObject Des endIndex); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +158,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextAnnotationsFileCitationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextAnnotationsFileCitationObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaTextContentAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(document.RootElement, options); } default: @@ -193,15 +177,20 @@ InternalMessageDeltaContentTextAnnotationsFileCitationObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentTextAnnotationsFileCitationObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextAnnotationsFileCitationObject internalMessageDeltaContentTextAnnotationsFileCitationObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(document.RootElement); + if (internalMessageDeltaContentTextAnnotationsFileCitationObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextAnnotationsFileCitationObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextAnnotationsFileCitationObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.cs index a96c66517..1db97ff06 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObject.cs @@ -9,13 +9,12 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFileCitationObject : InternalMessageDeltaTextContentAnnotation { - internal InternalMessageDeltaContentTextAnnotationsFileCitationObject(int index) + internal InternalMessageDeltaContentTextAnnotationsFileCitationObject(int index) : base("file_citation") { - Type = "file_citation"; Index = index; } - internal InternalMessageDeltaContentTextAnnotationsFileCitationObject(string type, IDictionary serializedAdditionalRawData, int index, string text, InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int? startIndex, int? endIndex) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentTextAnnotationsFileCitationObject(string @type, IDictionary additionalBinaryDataProperties, int index, string text, InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation fileCitation, int? startIndex, int? endIndex) : base(@type, additionalBinaryDataProperties) { Index = index; Text = text; @@ -24,14 +23,14 @@ internal InternalMessageDeltaContentTextAnnotationsFileCitationObject(string typ EndIndex = endIndex; } - internal InternalMessageDeltaContentTextAnnotationsFileCitationObject() - { - } - public int Index { get; } + public string Text { get; } + public InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation FileCitation { get; } + public int? StartIndex { get; } + public int? EndIndex { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs index 61580bfdb..51525935e 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalMessageDeltaContentTextAnnotationsFileCitationObj { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true && Optional.IsDefined(FileId)) + if (Optional.IsDefined(FileId) && _additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("quote") != true && Optional.IsDefined(Quote)) + if (Optional.IsDefined(Quote) && _additionalBinaryDataProperties?.ContainsKey("quote") != true) { writer.WritePropertyName("quote"u8); writer.WriteStringValue(Quote); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, options); } - internal static InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; string quote = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("quote"u8)) + if (prop.NameEquals("quote"u8)) { - quote = property.Value.GetString(); + quote = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(fileId, quote, serializedAdditionalRawData); + return new InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(fileId, quote, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation IPersis string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation internalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement); + if (internalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.cs index 8451e2157..85f914f54 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation() { } - internal InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(string fileId, string quote, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation(string fileId, string quote, IDictionary additionalBinaryDataProperties) { FileId = fileId; Quote = quote; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } + public string Quote { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.Serialization.cs index 1ed21a80d..2ab01dd19 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.Serialization.cs @@ -7,154 +7,136 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFilePathObject : IJsonModel { + internal InternalMessageDeltaContentTextAnnotationsFilePathObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextAnnotationsFilePathObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true && Optional.IsDefined(Text)) + if (Optional.IsDefined(Text) && _additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData?.ContainsKey("file_path") != true && Optional.IsDefined(FilePath)) + if (Optional.IsDefined(FilePath) && _additionalBinaryDataProperties?.ContainsKey("file_path") != true) { writer.WritePropertyName("file_path"u8); writer.WriteObjectValue(FilePath, options); } - if (SerializedAdditionalRawData?.ContainsKey("start_index") != true && Optional.IsDefined(StartIndex)) + if (Optional.IsDefined(StartIndex) && _additionalBinaryDataProperties?.ContainsKey("start_index") != true) { writer.WritePropertyName("start_index"u8); writer.WriteNumberValue(StartIndex.Value); } - if (SerializedAdditionalRawData?.ContainsKey("end_index") != true && Optional.IsDefined(EndIndex)) + if (Optional.IsDefined(EndIndex) && _additionalBinaryDataProperties?.ContainsKey("end_index") != true) { writer.WritePropertyName("end_index"u8); writer.WriteNumberValue(EndIndex.Value); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentTextAnnotationsFilePathObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextAnnotationsFilePathObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextAnnotationsFilePathObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaTextContentAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextAnnotationsFilePathObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(document.RootElement, options); } - internal static InternalMessageDeltaContentTextAnnotationsFilePathObject DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextAnnotationsFilePathObject DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_path"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string text = default; InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath filePath = default; int? startIndex = default; int? endIndex = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("index"u8)) { - text = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("file_path"u8)) + if (prop.NameEquals("text"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - filePath = InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(property.Value, options); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) + if (prop.NameEquals("file_path"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - startIndex = property.Value.GetInt32(); + filePath = InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(prop.Value, options); continue; } - if (property.NameEquals("end_index"u8)) + if (prop.NameEquals("start_index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - endIndex = property.Value.GetInt32(); + startIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("end_index"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalMessageDeltaContentTextAnnotationsFilePathObject( - type, - serializedAdditionalRawData, + @type, + additionalBinaryDataProperties, index, text, filePath, @@ -162,10 +144,11 @@ internal static InternalMessageDeltaContentTextAnnotationsFilePathObject Deseria endIndex); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +158,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextAnnotationsFilePathObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextAnnotationsFilePathObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaTextContentAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(document.RootElement, options); } default: @@ -193,15 +177,20 @@ InternalMessageDeltaContentTextAnnotationsFilePathObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentTextAnnotationsFilePathObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextAnnotationsFilePathObject internalMessageDeltaContentTextAnnotationsFilePathObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(document.RootElement); + if (internalMessageDeltaContentTextAnnotationsFilePathObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextAnnotationsFilePathObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextAnnotationsFilePathObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.cs index 92320c4f5..c729725fc 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObject.cs @@ -9,13 +9,12 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFilePathObject : InternalMessageDeltaTextContentAnnotation { - internal InternalMessageDeltaContentTextAnnotationsFilePathObject(int index) + internal InternalMessageDeltaContentTextAnnotationsFilePathObject(int index) : base("file_path") { - Type = "file_path"; Index = index; } - internal InternalMessageDeltaContentTextAnnotationsFilePathObject(string type, IDictionary serializedAdditionalRawData, int index, string text, InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath filePath, int? startIndex, int? endIndex) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentTextAnnotationsFilePathObject(string @type, IDictionary additionalBinaryDataProperties, int index, string text, InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath filePath, int? startIndex, int? endIndex) : base(@type, additionalBinaryDataProperties) { Index = index; Text = text; @@ -24,14 +23,14 @@ internal InternalMessageDeltaContentTextAnnotationsFilePathObject(string type, I EndIndex = endIndex; } - internal InternalMessageDeltaContentTextAnnotationsFilePathObject() - { - } - public int Index { get; } + public string Text { get; } + public InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath FilePath { get; } + public int? StartIndex { get; } + public int? EndIndex { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.Serialization.cs index 2cabf1597..64af2f141 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ internal partial class InternalMessageDeltaContentTextAnnotationsFilePathObjectF { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true && Optional.IsDefined(FileId)) + if (Optional.IsDefined(FileId) && _additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(document.RootElement, options); } - internal static InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(fileId, serializedAdditionalRawData); + return new InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(fileId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +103,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(document.RootElement, options); } default: @@ -119,15 +122,20 @@ InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath IPersistableMod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath internalMessageDeltaContentTextAnnotationsFilePathObjectFilePath) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(document.RootElement); + if (internalMessageDeltaContentTextAnnotationsFilePathObjectFilePath == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextAnnotationsFilePathObjectFilePath, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.cs b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.cs index 3e41f99b0..89223887d 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath() { } - internal InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(string fileId, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath(string fileId, IDictionary additionalBinaryDataProperties) { FileId = fileId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextObject.Serialization.cs index 75983efa0..7eebdd746 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextObject.Serialization.cs @@ -7,117 +7,100 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextObject : IJsonModel { + internal InternalMessageDeltaContentTextObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true && Optional.IsDefined(Text)) + if (Optional.IsDefined(Text) && _additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteObjectValue(Text, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalMessageDeltaContentTextObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextObject)JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextObject(document.RootElement, options); } - internal static InternalMessageDeltaContentTextObject DeserializeInternalMessageDeltaContentTextObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextObject DeserializeInternalMessageDeltaContentTextObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "text"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; InternalMessageDeltaContentTextObjectText text = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - text = InternalMessageDeltaContentTextObjectText.DeserializeInternalMessageDeltaContentTextObjectText(property.Value, options); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("text"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + text = InternalMessageDeltaContentTextObjectText.DeserializeInternalMessageDeltaContentTextObjectText(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentTextObject(type, serializedAdditionalRawData, index, text); + return new InternalMessageDeltaContentTextObject(@type, additionalBinaryDataProperties, index, text); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -127,15 +110,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalMessageDeltaContentTextObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageDeltaContentTextObject)PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextObject(document.RootElement, options); } default: @@ -145,15 +129,20 @@ InternalMessageDeltaContentTextObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageDeltaContentTextObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextObject internalMessageDeltaContentTextObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextObject(document.RootElement); + if (internalMessageDeltaContentTextObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextObject.cs b/src/Generated/Models/InternalMessageDeltaContentTextObject.cs index a4154f431..f8546832f 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextObject.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextObject.cs @@ -9,23 +9,19 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextObject : InternalMessageDeltaContent { - internal InternalMessageDeltaContentTextObject(int index) + internal InternalMessageDeltaContentTextObject(int index) : base("text") { - Type = "text"; Index = index; } - internal InternalMessageDeltaContentTextObject(string type, IDictionary serializedAdditionalRawData, int index, InternalMessageDeltaContentTextObjectText text) : base(type, serializedAdditionalRawData) + internal InternalMessageDeltaContentTextObject(string @type, IDictionary additionalBinaryDataProperties, int index, InternalMessageDeltaContentTextObjectText text) : base(@type, additionalBinaryDataProperties) { Index = index; Text = text; } - internal InternalMessageDeltaContentTextObject() - { - } - public int Index { get; } + public InternalMessageDeltaContentTextObjectText Text { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextObjectText.Serialization.cs b/src/Generated/Models/InternalMessageDeltaContentTextObjectText.Serialization.cs index fbc18edf5..3a75de3db 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextObjectText.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextObjectText.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,36 @@ internal partial class InternalMessageDeltaContentTextObjectText : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContentTextObjectText)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("value") != true && Optional.IsDefined(Value)) + if (Optional.IsDefined(Value) && _additionalBinaryDataProperties?.ContainsKey("value") != true) { writer.WritePropertyName("value"u8); writer.WriteStringValue(Value); } - if (SerializedAdditionalRawData?.ContainsKey("annotations") != true && Optional.IsCollectionDefined(Annotations)) + if (Optional.IsCollectionDefined(Annotations) && _additionalBinaryDataProperties?.ContainsKey("annotations") != true) { writer.WritePropertyName("annotations"u8); writer.WriteStartArray(); - foreach (var item in Annotations) + foreach (InternalMessageDeltaTextContentAnnotation item in Annotations) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,48 +61,45 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaContentTextObjectText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContentTextObjectText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaContentTextObjectText JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContentTextObjectText)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContentTextObjectText(document.RootElement, options); } - internal static InternalMessageDeltaContentTextObjectText DeserializeInternalMessageDeltaContentTextObjectText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaContentTextObjectText DeserializeInternalMessageDeltaContentTextObjectText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string value = default; - IReadOnlyList annotations = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList annotations = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("value"u8)) + if (prop.NameEquals("value"u8)) { - value = property.Value.GetString(); + value = prop.Value.GetString(); continue; } - if (property.NameEquals("annotations"u8)) + if (prop.NameEquals("annotations"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalMessageDeltaTextContentAnnotation.DeserializeInternalMessageDeltaTextContentAnnotation(item, options)); } @@ -105,18 +108,17 @@ internal static InternalMessageDeltaContentTextObjectText DeserializeInternalMes } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaContentTextObjectText(value, annotations ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalMessageDeltaContentTextObjectText(value, annotations ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -126,15 +128,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalMessageDeltaContentTextObjectText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContentTextObjectText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaContentTextObjectText 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContentTextObjectText(document.RootElement, options); } default: @@ -144,15 +147,20 @@ InternalMessageDeltaContentTextObjectText IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaContentTextObjectText FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaContentTextObjectText internalMessageDeltaContentTextObjectText) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaContentTextObjectText(document.RootElement); + if (internalMessageDeltaContentTextObjectText == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaContentTextObjectText, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaContentTextObjectText(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaContentTextObjectText(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaContentTextObjectText.cs b/src/Generated/Models/InternalMessageDeltaContentTextObjectText.cs index f2b651436..80c395a14 100644 --- a/src/Generated/Models/InternalMessageDeltaContentTextObjectText.cs +++ b/src/Generated/Models/InternalMessageDeltaContentTextObjectText.cs @@ -4,25 +4,34 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaContentTextObjectText { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaContentTextObjectText() { Annotations = new ChangeTrackingList(); } - internal InternalMessageDeltaContentTextObjectText(string value, IReadOnlyList annotations, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaContentTextObjectText(string value, IList annotations, IDictionary additionalBinaryDataProperties) { Value = value; Annotations = annotations; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Value { get; } - public IReadOnlyList Annotations { get; } + + public IList Annotations { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaObject.Serialization.cs b/src/Generated/Models/InternalMessageDeltaObject.Serialization.cs index 1bba65403..af9621cc5 100644 --- a/src/Generated/Models/InternalMessageDeltaObject.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaObject.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaObject : IJsonModel { + internal InternalMessageDeltaObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteObjectValue(Delta, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,25 +65,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaObject(document.RootElement, options); } - internal static InternalMessageDeltaObject DeserializeInternalMessageDeltaObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaObject DeserializeInternalMessageDeltaObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -81,39 +89,37 @@ internal static InternalMessageDeltaObject DeserializeInternalMessageDeltaObject string id = default; InternalMessageDeltaObjectObject @object = default; InternalMessageDeltaObjectDelta delta = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalMessageDeltaObjectObject(property.Value.GetString()); + @object = new InternalMessageDeltaObjectObject(prop.Value.GetString()); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("delta"u8)) { - delta = InternalMessageDeltaObjectDelta.DeserializeInternalMessageDeltaObjectDelta(property.Value, options); + delta = InternalMessageDeltaObjectDelta.DeserializeInternalMessageDeltaObjectDelta(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaObject(id, @object, delta, serializedAdditionalRawData); + return new InternalMessageDeltaObject(id, @object, delta, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalMessageDeltaObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaObject(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalMessageDeltaObject IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaObject internalMessageDeltaObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaObject(document.RootElement); + if (internalMessageDeltaObject == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaObject, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaObject.cs b/src/Generated/Models/InternalMessageDeltaObject.cs index 92dad3abb..a9e15adda 100644 --- a/src/Generated/Models/InternalMessageDeltaObject.cs +++ b/src/Generated/Models/InternalMessageDeltaObject.cs @@ -9,31 +9,32 @@ namespace OpenAI.Assistants { internal partial class InternalMessageDeltaObject { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaObject(string id, InternalMessageDeltaObjectDelta delta) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(delta, nameof(delta)); - Id = id; Delta = delta; } - internal InternalMessageDeltaObject(string id, InternalMessageDeltaObjectObject @object, InternalMessageDeltaObjectDelta delta, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaObject(string id, InternalMessageDeltaObjectObject @object, InternalMessageDeltaObjectDelta delta, IDictionary additionalBinaryDataProperties) { Id = id; Object = @object; Delta = delta; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalMessageDeltaObject() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } - public InternalMessageDeltaObjectObject Object { get; } = InternalMessageDeltaObjectObject.ThreadMessageDelta; + + public InternalMessageDeltaObjectObject Object { get; } = "thread.message.delta"; public InternalMessageDeltaObjectDelta Delta { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageDeltaObjectDelta.Serialization.cs b/src/Generated/Models/InternalMessageDeltaObjectDelta.Serialization.cs index 93e19568b..6d2f67e65 100644 --- a/src/Generated/Models/InternalMessageDeltaObjectDelta.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaObjectDelta.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,36 @@ internal partial class InternalMessageDeltaObjectDelta : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaObjectDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("content") != true && Optional.IsCollectionDefined(Content)) + if (Optional.IsCollectionDefined(Content) && _additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (InternalMessageDeltaContent item in Content) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(Role) && _additionalBinaryDataProperties?.ContainsKey("role") != true) + { + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.Value.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,72 +61,68 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaObjectDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaObjectDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaObjectDelta JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaObjectDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaObjectDelta(document.RootElement, options); } - internal static InternalMessageDeltaObjectDelta DeserializeInternalMessageDeltaObjectDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaObjectDelta DeserializeInternalMessageDeltaObjectDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - MessageRole role = default; - IReadOnlyList content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList content = default; + Assistants.MessageRole? role = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) + if (prop.NameEquals("content"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - role = property.Value.GetString().ToMessageRole(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(InternalMessageDeltaContent.DeserializeInternalMessageDeltaContent(item, options)); + } + content = array; continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(InternalMessageDeltaContent.DeserializeInternalMessageDeltaContent(item, options)); - } - content = array; + role = prop.Value.GetString().ToMessageRole(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageDeltaObjectDelta(role, content ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalMessageDeltaObjectDelta(content ?? new ChangeTrackingList(), role, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -130,15 +132,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalMessageDeltaObjectDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaObjectDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaObjectDelta 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaObjectDelta(document.RootElement, options); } default: @@ -148,15 +151,20 @@ InternalMessageDeltaObjectDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaObjectDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaObjectDelta internalMessageDeltaObjectDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaObjectDelta(document.RootElement); + if (internalMessageDeltaObjectDelta == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaObjectDelta, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaObjectDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaObjectDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaObjectDelta.cs b/src/Generated/Models/InternalMessageDeltaObjectDelta.cs index 63a7af934..71995269f 100644 --- a/src/Generated/Models/InternalMessageDeltaObjectDelta.cs +++ b/src/Generated/Models/InternalMessageDeltaObjectDelta.cs @@ -4,23 +4,32 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageDeltaObjectDelta { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageDeltaObjectDelta() { Content = new ChangeTrackingList(); } - internal InternalMessageDeltaObjectDelta(MessageRole role, IReadOnlyList content, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaObjectDelta(IList content, Assistants.MessageRole? role, IDictionary additionalBinaryDataProperties) { - Role = role; Content = content; - SerializedAdditionalRawData = serializedAdditionalRawData; + Role = role; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + public IList Content { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public IReadOnlyList Content { get; } } } diff --git a/src/Generated/Models/InternalMessageDeltaObjectDeltaRole.cs b/src/Generated/Models/InternalMessageDeltaObjectDeltaRole.cs index d477fcb93..d71bd5357 100644 --- a/src/Generated/Models/InternalMessageDeltaObjectDeltaRole.cs +++ b/src/Generated/Models/InternalMessageDeltaObjectDeltaRole.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageDeltaObjectDeltaRole : IEquatable { private readonly string _value; + private const string UserValue = "user"; + private const string AssistantValue = "assistant"; public InternalMessageDeltaObjectDeltaRole(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UserValue = "user"; - private const string AssistantValue = "assistant"; + _value = value; + } public static InternalMessageDeltaObjectDeltaRole User { get; } = new InternalMessageDeltaObjectDeltaRole(UserValue); + public static InternalMessageDeltaObjectDeltaRole Assistant { get; } = new InternalMessageDeltaObjectDeltaRole(AssistantValue); + public static bool operator ==(InternalMessageDeltaObjectDeltaRole left, InternalMessageDeltaObjectDeltaRole right) => left.Equals(right); + public static bool operator !=(InternalMessageDeltaObjectDeltaRole left, InternalMessageDeltaObjectDeltaRole right) => !left.Equals(right); + public static implicit operator InternalMessageDeltaObjectDeltaRole(string value) => new InternalMessageDeltaObjectDeltaRole(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageDeltaObjectDeltaRole other && Equals(other); + public bool Equals(InternalMessageDeltaObjectDeltaRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageDeltaObjectObject.cs b/src/Generated/Models/InternalMessageDeltaObjectObject.cs index a420957ec..2efee4df9 100644 --- a/src/Generated/Models/InternalMessageDeltaObjectObject.cs +++ b/src/Generated/Models/InternalMessageDeltaObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageDeltaObjectObject : IEquatable { private readonly string _value; + private const string ThreadMessageDeltaValue = "thread.message.delta"; public InternalMessageDeltaObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadMessageDeltaValue = "thread.message.delta"; + _value = value; + } public static InternalMessageDeltaObjectObject ThreadMessageDelta { get; } = new InternalMessageDeltaObjectObject(ThreadMessageDeltaValue); + public static bool operator ==(InternalMessageDeltaObjectObject left, InternalMessageDeltaObjectObject right) => left.Equals(right); + public static bool operator !=(InternalMessageDeltaObjectObject left, InternalMessageDeltaObjectObject right) => !left.Equals(right); + public static implicit operator InternalMessageDeltaObjectObject(string value) => new InternalMessageDeltaObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageDeltaObjectObject other && Equals(other); + public bool Equals(InternalMessageDeltaObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.Serialization.cs b/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.Serialization.cs index 1382bacd8..447aa246c 100644 --- a/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.Serialization.cs +++ b/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownMessageDeltaTextContentAnnotation))] - internal partial class InternalMessageDeltaTextContentAnnotation : IJsonModel + internal abstract partial class InternalMessageDeltaTextContentAnnotation : IJsonModel { + internal InternalMessageDeltaTextContentAnnotation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaTextContentAnnotation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalMessageDeltaTextContentAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaTextContentAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageDeltaTextContentAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaTextContentAnnotation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement, options); } - internal static InternalMessageDeltaTextContentAnnotation DeserializeInternalMessageDeltaTextContentAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageDeltaTextContentAnnotation DeserializeInternalMessageDeltaTextContentAnnotation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "file_citation": return InternalMessageDeltaContentTextAnnotationsFileCitationObject.DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(element, options); - case "file_path": return InternalMessageDeltaContentTextAnnotationsFilePathObject.DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(element, options); + case "file_citation": + return InternalMessageDeltaContentTextAnnotationsFileCitationObject.DeserializeInternalMessageDeltaContentTextAnnotationsFileCitationObject(element, options); + case "file_path": + return InternalMessageDeltaContentTextAnnotationsFilePathObject.DeserializeInternalMessageDeltaContentTextAnnotationsFilePathObject(element, options); } } return UnknownMessageDeltaTextContentAnnotation.DeserializeUnknownMessageDeltaTextContentAnnotation(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalMessageDeltaTextContentAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaTextContentAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageDeltaTextContentAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement, options); } default: @@ -110,15 +122,20 @@ InternalMessageDeltaTextContentAnnotation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageDeltaTextContentAnnotation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageDeltaTextContentAnnotation internalMessageDeltaTextContentAnnotation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement); + if (internalMessageDeltaTextContentAnnotation == null) + { + return null; + } + return BinaryContent.Create(internalMessageDeltaTextContentAnnotation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageDeltaTextContentAnnotation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.cs b/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.cs index 34640b4dc..d34f19001 100644 --- a/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.cs +++ b/src/Generated/Models/InternalMessageDeltaTextContentAnnotation.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal abstract partial class InternalMessageDeltaTextContentAnnotation { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalMessageDeltaTextContentAnnotation() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalMessageDeltaTextContentAnnotation(string @type) { + Type = @type; } - internal InternalMessageDeltaTextContentAnnotation(string type, IDictionary serializedAdditionalRawData) + internal InternalMessageDeltaTextContentAnnotation(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageImageFileContent.Serialization.cs b/src/Generated/Models/InternalMessageImageFileContent.Serialization.cs index 8a176fdbf..c831eb317 100644 --- a/src/Generated/Models/InternalMessageImageFileContent.Serialization.cs +++ b/src/Generated/Models/InternalMessageImageFileContent.Serialization.cs @@ -7,61 +7,83 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageImageFileContent : IJsonModel { - InternalMessageImageFileContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalMessageImageFileContent() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalMessageImageFileContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalMessageImageFileContent)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type); } + if (_additionalBinaryDataProperties?.ContainsKey("image_file") != true) + { + writer.WritePropertyName("image_file"u8); + writer.WriteObjectValue(_imageFile, options); + } + } + InternalMessageImageFileContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageImageFileContent)JsonModelCreateCore(ref reader, options); + + protected override MessageContent 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(InternalMessageImageFileContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageImageFileContent(document.RootElement, options); } - internal static InternalMessageImageFileContent DeserializeInternalMessageImageFileContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageImageFileContent DeserializeInternalMessageImageFileContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = default; InternalMessageContentItemFileObjectImageFile imageFile = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("image_file"u8)) + if (prop.NameEquals("image_file"u8)) { - imageFile = InternalMessageContentItemFileObjectImageFile.DeserializeInternalMessageContentItemFileObjectImageFile(property.Value, options); + imageFile = InternalMessageContentItemFileObjectImageFile.DeserializeInternalMessageContentItemFileObjectImageFile(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageImageFileContent(serializedAdditionalRawData, type, imageFile); + return new InternalMessageImageFileContent(additionalBinaryDataProperties, @type, imageFile); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalMessageImageFileContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageImageFileContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageImageFileContent)PersistableModelCreateCore(data, options); + protected override MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageImageFileContent(document.RootElement, options); } default: @@ -89,15 +112,20 @@ InternalMessageImageFileContent IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageImageFileContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageImageFileContent internalMessageImageFileContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageImageFileContent(document.RootElement); + if (internalMessageImageFileContent == null) + { + return null; + } + return BinaryContent.Create(internalMessageImageFileContent, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageImageFileContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageImageFileContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageImageFileContent.cs b/src/Generated/Models/InternalMessageImageFileContent.cs index 0daac586c..41ae17f04 100644 --- a/src/Generated/Models/InternalMessageImageFileContent.cs +++ b/src/Generated/Models/InternalMessageImageFileContent.cs @@ -9,14 +9,10 @@ namespace OpenAI.Assistants { internal partial class InternalMessageImageFileContent : MessageContent { - internal InternalMessageImageFileContent(IDictionary serializedAdditionalRawData, string type, InternalMessageContentItemFileObjectImageFile imageFile) : base(serializedAdditionalRawData) + internal InternalMessageImageFileContent(IDictionary additionalBinaryDataProperties, string @type, InternalMessageContentItemFileObjectImageFile imageFile) : base(additionalBinaryDataProperties) { - _type = type; + _type = @type; _imageFile = imageFile; } - - internal InternalMessageImageFileContent() - { - } } } diff --git a/src/Generated/Models/InternalMessageImageUrlContent.Serialization.cs b/src/Generated/Models/InternalMessageImageUrlContent.Serialization.cs index bbf8977d0..decb82a1b 100644 --- a/src/Generated/Models/InternalMessageImageUrlContent.Serialization.cs +++ b/src/Generated/Models/InternalMessageImageUrlContent.Serialization.cs @@ -7,61 +7,83 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageImageUrlContent : IJsonModel { - InternalMessageImageUrlContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalMessageImageUrlContent() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalMessageImageUrlContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalMessageImageUrlContent)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type); } + if (_additionalBinaryDataProperties?.ContainsKey("image_url") != true) + { + writer.WritePropertyName("image_url"u8); + writer.WriteObjectValue(_imageUrl, options); + } + } + InternalMessageImageUrlContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageImageUrlContent)JsonModelCreateCore(ref reader, options); + + protected override MessageContent 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(InternalMessageImageUrlContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageImageUrlContent(document.RootElement, options); } - internal static InternalMessageImageUrlContent DeserializeInternalMessageImageUrlContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageImageUrlContent DeserializeInternalMessageImageUrlContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = default; InternalMessageContentImageUrlObjectImageUrl imageUrl = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("image_url"u8)) + if (prop.NameEquals("image_url"u8)) { - imageUrl = InternalMessageContentImageUrlObjectImageUrl.DeserializeInternalMessageContentImageUrlObjectImageUrl(property.Value, options); + imageUrl = InternalMessageContentImageUrlObjectImageUrl.DeserializeInternalMessageContentImageUrlObjectImageUrl(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageImageUrlContent(serializedAdditionalRawData, type, imageUrl); + return new InternalMessageImageUrlContent(additionalBinaryDataProperties, @type, imageUrl); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - InternalMessageImageUrlContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageImageUrlContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageImageUrlContent)PersistableModelCreateCore(data, options); + protected override MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageImageUrlContent(document.RootElement, options); } default: @@ -89,15 +112,20 @@ InternalMessageImageUrlContent IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageImageUrlContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageImageUrlContent internalMessageImageUrlContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageImageUrlContent(document.RootElement); + if (internalMessageImageUrlContent == null) + { + return null; + } + return BinaryContent.Create(internalMessageImageUrlContent, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageImageUrlContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageImageUrlContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageImageUrlContent.cs b/src/Generated/Models/InternalMessageImageUrlContent.cs index beb249485..dd2db88a2 100644 --- a/src/Generated/Models/InternalMessageImageUrlContent.cs +++ b/src/Generated/Models/InternalMessageImageUrlContent.cs @@ -9,14 +9,10 @@ namespace OpenAI.Assistants { internal partial class InternalMessageImageUrlContent : MessageContent { - internal InternalMessageImageUrlContent(IDictionary serializedAdditionalRawData, string type, InternalMessageContentImageUrlObjectImageUrl imageUrl) : base(serializedAdditionalRawData) + internal InternalMessageImageUrlContent(IDictionary additionalBinaryDataProperties, string @type, InternalMessageContentImageUrlObjectImageUrl imageUrl) : base(additionalBinaryDataProperties) { - _type = type; + _type = @type; _imageUrl = imageUrl; } - - internal InternalMessageImageUrlContent() - { - } } } diff --git a/src/Generated/Models/InternalMessageObjectAttachment.Serialization.cs b/src/Generated/Models/InternalMessageObjectAttachment.Serialization.cs index 3d0849f9a..cb5cc7e63 100644 --- a/src/Generated/Models/InternalMessageObjectAttachment.Serialization.cs +++ b/src/Generated/Models/InternalMessageObjectAttachment.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,23 +15,28 @@ internal partial class InternalMessageObjectAttachment : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageObjectAttachment)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true && Optional.IsDefined(FileId)) + if (Optional.IsDefined(FileId) && _additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (BinaryData item in Tools) { if (item == null) { @@ -38,7 +44,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo continue; } #if NET6_0_OR_GREATER - writer.WriteRawValue(item); + writer.WriteRawValue(item); #else using (JsonDocument document = JsonDocument.Parse(item)) { @@ -48,9 +54,9 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -58,7 +64,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -67,48 +73,45 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalMessageObjectAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageObjectAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalMessageObjectAttachment JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageObjectAttachment)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageObjectAttachment(document.RootElement, options); } - internal static InternalMessageObjectAttachment DeserializeInternalMessageObjectAttachment(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageObjectAttachment DeserializeInternalMessageObjectAttachment(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IReadOnlyList tools = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList tools = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { @@ -124,18 +127,17 @@ internal static InternalMessageObjectAttachment DeserializeInternalMessageObject } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageObjectAttachment(fileId, tools ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalMessageObjectAttachment(fileId, tools ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -145,15 +147,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalMessageObjectAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageObjectAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalMessageObjectAttachment 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageObjectAttachment(document.RootElement, options); } default: @@ -163,15 +166,20 @@ InternalMessageObjectAttachment IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalMessageObjectAttachment FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageObjectAttachment internalMessageObjectAttachment) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageObjectAttachment(document.RootElement); + if (internalMessageObjectAttachment == null) + { + return null; + } + return BinaryContent.Create(internalMessageObjectAttachment, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalMessageObjectAttachment(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageObjectAttachment(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageObjectAttachment.cs b/src/Generated/Models/InternalMessageObjectAttachment.cs index 1e92848e3..6255505fb 100644 --- a/src/Generated/Models/InternalMessageObjectAttachment.cs +++ b/src/Generated/Models/InternalMessageObjectAttachment.cs @@ -4,25 +4,34 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageObjectAttachment { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalMessageObjectAttachment() { Tools = new ChangeTrackingList(); } - internal InternalMessageObjectAttachment(string fileId, IReadOnlyList tools, IDictionary serializedAdditionalRawData) + internal InternalMessageObjectAttachment(string fileId, IList tools, IDictionary additionalBinaryDataProperties) { FileId = fileId; Tools = tools; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } - public IReadOnlyList Tools { get; } + + public IList Tools { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalMessageObjectObject.cs b/src/Generated/Models/InternalMessageObjectObject.cs index e419910c5..76edcd658 100644 --- a/src/Generated/Models/InternalMessageObjectObject.cs +++ b/src/Generated/Models/InternalMessageObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageObjectObject : IEquatable { private readonly string _value; + private const string ThreadMessageValue = "thread.message"; public InternalMessageObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadMessageValue = "thread.message"; + _value = value; + } public static InternalMessageObjectObject ThreadMessage { get; } = new InternalMessageObjectObject(ThreadMessageValue); + public static bool operator ==(InternalMessageObjectObject left, InternalMessageObjectObject right) => left.Equals(right); + public static bool operator !=(InternalMessageObjectObject left, InternalMessageObjectObject right) => !left.Equals(right); + public static implicit operator InternalMessageObjectObject(string value) => new InternalMessageObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageObjectObject other && Equals(other); + public bool Equals(InternalMessageObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageObjectRole.cs b/src/Generated/Models/InternalMessageObjectRole.cs index 91e68a9de..972b10975 100644 --- a/src/Generated/Models/InternalMessageObjectRole.cs +++ b/src/Generated/Models/InternalMessageObjectRole.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageObjectRole : IEquatable { private readonly string _value; + private const string UserValue = "user"; + private const string AssistantValue = "assistant"; public InternalMessageObjectRole(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UserValue = "user"; - private const string AssistantValue = "assistant"; + _value = value; + } public static InternalMessageObjectRole User { get; } = new InternalMessageObjectRole(UserValue); + public static InternalMessageObjectRole Assistant { get; } = new InternalMessageObjectRole(AssistantValue); + public static bool operator ==(InternalMessageObjectRole left, InternalMessageObjectRole right) => left.Equals(right); + public static bool operator !=(InternalMessageObjectRole left, InternalMessageObjectRole right) => !left.Equals(right); + public static implicit operator InternalMessageObjectRole(string value) => new InternalMessageObjectRole(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageObjectRole other && Equals(other); + public bool Equals(InternalMessageObjectRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs b/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs index 6e3c9846f..a59102fb3 100644 --- a/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs +++ b/src/Generated/Models/InternalMessageRefusalContent.Serialization.cs @@ -7,61 +7,83 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalMessageRefusalContent : IJsonModel { - InternalMessageRefusalContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalMessageRefusalContent() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalMessageRefusalContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalMessageRefusalContent)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("refusal") != true) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(InternalRefusal); } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type); + } + } + InternalMessageRefusalContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalMessageRefusalContent)JsonModelCreateCore(ref reader, options); + + protected override MessageContent 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(InternalMessageRefusalContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageRefusalContent(document.RootElement, options); } - internal static InternalMessageRefusalContent DeserializeInternalMessageRefusalContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalMessageRefusalContent DeserializeInternalMessageRefusalContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - string refusal = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string internalRefusal = default; + string @type = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("refusal"u8)) { - type = property.Value.GetString(); + internalRefusal = prop.Value.GetString(); continue; } - if (property.NameEquals("refusal"u8)) + if (prop.NameEquals("type"u8)) { - refusal = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalMessageRefusalContent(serializedAdditionalRawData, type, refusal); + return new InternalMessageRefusalContent(additionalBinaryDataProperties, internalRefusal, @type); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - InternalMessageRefusalContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageRefusalContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalMessageRefusalContent)PersistableModelCreateCore(data, options); + protected override MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageRefusalContent(document.RootElement, options); } default: @@ -89,15 +112,20 @@ InternalMessageRefusalContent IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalMessageRefusalContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalMessageRefusalContent internalMessageRefusalContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMessageRefusalContent(document.RootElement); + if (internalMessageRefusalContent == null) + { + return null; + } + return BinaryContent.Create(internalMessageRefusalContent, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalMessageRefusalContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalMessageRefusalContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalMessageRefusalContent.cs b/src/Generated/Models/InternalMessageRefusalContent.cs index dc6f0e0af..cf5028d08 100644 --- a/src/Generated/Models/InternalMessageRefusalContent.cs +++ b/src/Generated/Models/InternalMessageRefusalContent.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { @@ -16,14 +17,10 @@ public InternalMessageRefusalContent(string internalRefusal) InternalRefusal = internalRefusal; } - internal InternalMessageRefusalContent(IDictionary serializedAdditionalRawData, string type, string internalRefusal) : base(serializedAdditionalRawData) + internal InternalMessageRefusalContent(IDictionary additionalBinaryDataProperties, string internalRefusal, string @type) : base(additionalBinaryDataProperties) { - _type = type; InternalRefusal = internalRefusal; - } - - internal InternalMessageRefusalContent() - { + _type = @type; } } } diff --git a/src/Generated/Models/InternalMessageRequestContentTextObjectType.cs b/src/Generated/Models/InternalMessageRequestContentTextObjectType.cs index f41f3c083..b7caeebc4 100644 --- a/src/Generated/Models/InternalMessageRequestContentTextObjectType.cs +++ b/src/Generated/Models/InternalMessageRequestContentTextObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalMessageRequestContentTextObjectType : IEquatable { private readonly string _value; + private const string TextValue = "text"; public InternalMessageRequestContentTextObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextValue = "text"; + _value = value; + } public static InternalMessageRequestContentTextObjectType Text { get; } = new InternalMessageRequestContentTextObjectType(TextValue); + public static bool operator ==(InternalMessageRequestContentTextObjectType left, InternalMessageRequestContentTextObjectType right) => left.Equals(right); + public static bool operator !=(InternalMessageRequestContentTextObjectType left, InternalMessageRequestContentTextObjectType right) => !left.Equals(right); + public static implicit operator InternalMessageRequestContentTextObjectType(string value) => new InternalMessageRequestContentTextObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalMessageRequestContentTextObjectType other && Equals(other); + public bool Equals(InternalMessageRequestContentTextObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalModelObject.cs b/src/Generated/Models/InternalModelObject.cs index 79b9cefab..eac208570 100644 --- a/src/Generated/Models/InternalModelObject.cs +++ b/src/Generated/Models/InternalModelObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Models { internal readonly partial struct InternalModelObject : IEquatable { private readonly string _value; + private const string ModelValue = "model"; public InternalModelObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ModelValue = "model"; + _value = value; + } public static InternalModelObject Model { get; } = new InternalModelObject(ModelValue); + public static bool operator ==(InternalModelObject left, InternalModelObject right) => left.Equals(right); + public static bool operator !=(InternalModelObject left, InternalModelObject right) => !left.Equals(right); + public static implicit operator InternalModelObject(string value) => new InternalModelObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalModelObject other && Equals(other); + public bool Equals(InternalModelObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalModerationCategories.Serialization.cs b/src/Generated/Models/InternalModerationCategories.Serialization.cs index 468017278..f2979e342 100644 --- a/src/Generated/Models/InternalModerationCategories.Serialization.cs +++ b/src/Generated/Models/InternalModerationCategories.Serialization.cs @@ -7,88 +7,98 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalModerationCategories : IJsonModel { + internal InternalModerationCategories() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModerationCategories)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("hate") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate") != true) { writer.WritePropertyName("hate"u8); writer.WriteBooleanValue(Hate); } - if (SerializedAdditionalRawData?.ContainsKey("hate/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate/threatening") != true) { writer.WritePropertyName("hate/threatening"u8); writer.WriteBooleanValue(HateThreatening); } - if (SerializedAdditionalRawData?.ContainsKey("harassment") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment") != true) { writer.WritePropertyName("harassment"u8); writer.WriteBooleanValue(Harassment); } - if (SerializedAdditionalRawData?.ContainsKey("harassment/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment/threatening") != true) { writer.WritePropertyName("harassment/threatening"u8); writer.WriteBooleanValue(HarassmentThreatening); } - if (SerializedAdditionalRawData?.ContainsKey("illicit") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit") != true) { writer.WritePropertyName("illicit"u8); writer.WriteBooleanValue(Illicit); } - if (SerializedAdditionalRawData?.ContainsKey("illicit/violent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit/violent") != true) { writer.WritePropertyName("illicit/violent"u8); writer.WriteBooleanValue(IllicitViolent); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm") != true) { writer.WritePropertyName("self-harm"u8); writer.WriteBooleanValue(SelfHarm); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/intent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/intent") != true) { writer.WritePropertyName("self-harm/intent"u8); writer.WriteBooleanValue(SelfHarmIntent); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/instructions") != true) { writer.WritePropertyName("self-harm/instructions"u8); writer.WriteBooleanValue(SelfHarmInstructions); } - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual") != true) { writer.WritePropertyName("sexual"u8); writer.WriteBooleanValue(Sexual); } - if (SerializedAdditionalRawData?.ContainsKey("sexual/minors") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual/minors") != true) { writer.WritePropertyName("sexual/minors"u8); writer.WriteBooleanValue(SexualMinors); } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence") != true) { writer.WritePropertyName("violence"u8); writer.WriteBooleanValue(Violence); } - if (SerializedAdditionalRawData?.ContainsKey("violence/graphic") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence/graphic") != true) { writer.WritePropertyName("violence/graphic"u8); writer.WriteBooleanValue(ViolenceGraphic); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -96,7 +106,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -105,25 +115,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - InternalModerationCategories IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModerationCategories IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModerationCategories JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModerationCategories)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModerationCategories(document.RootElement, options); } - internal static InternalModerationCategories DeserializeInternalModerationCategories(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModerationCategories DeserializeInternalModerationCategories(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -141,82 +149,79 @@ internal static InternalModerationCategories DeserializeInternalModerationCatego bool sexualMinors = default; bool violence = default; bool violenceGraphic = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("hate"u8)) + if (prop.NameEquals("hate"u8)) { - hate = property.Value.GetBoolean(); + hate = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("hate/threatening"u8)) + if (prop.NameEquals("hate/threatening"u8)) { - hateThreatening = property.Value.GetBoolean(); + hateThreatening = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("harassment"u8)) + if (prop.NameEquals("harassment"u8)) { - harassment = property.Value.GetBoolean(); + harassment = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("harassment/threatening"u8)) + if (prop.NameEquals("harassment/threatening"u8)) { - harassmentThreatening = property.Value.GetBoolean(); + harassmentThreatening = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("illicit"u8)) + if (prop.NameEquals("illicit"u8)) { - illicit = property.Value.GetBoolean(); + illicit = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("illicit/violent"u8)) + if (prop.NameEquals("illicit/violent"u8)) { - illicitViolent = property.Value.GetBoolean(); + illicitViolent = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("self-harm"u8)) + if (prop.NameEquals("self-harm"u8)) { - selfHarm = property.Value.GetBoolean(); + selfHarm = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("self-harm/intent"u8)) + if (prop.NameEquals("self-harm/intent"u8)) { - selfHarmIntent = property.Value.GetBoolean(); + selfHarmIntent = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("self-harm/instructions"u8)) + if (prop.NameEquals("self-harm/instructions"u8)) { - selfHarmInstructions = property.Value.GetBoolean(); + selfHarmInstructions = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("sexual"u8)) + if (prop.NameEquals("sexual"u8)) { - sexual = property.Value.GetBoolean(); + sexual = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("sexual/minors"u8)) + if (prop.NameEquals("sexual/minors"u8)) { - sexualMinors = property.Value.GetBoolean(); + sexualMinors = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("violence"u8)) + if (prop.NameEquals("violence"u8)) { - violence = property.Value.GetBoolean(); + violence = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("violence/graphic"u8)) + if (prop.NameEquals("violence/graphic"u8)) { - violenceGraphic = property.Value.GetBoolean(); + violenceGraphic = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalModerationCategories( hate, hateThreatening, @@ -231,13 +236,14 @@ internal static InternalModerationCategories DeserializeInternalModerationCatego sexualMinors, violence, violenceGraphic, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -247,15 +253,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalModerationCategories IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModerationCategories IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModerationCategories 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModerationCategories(document.RootElement, options); } default: @@ -265,15 +272,20 @@ InternalModerationCategories IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModerationCategories FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModerationCategories internalModerationCategories) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModerationCategories(document.RootElement); + if (internalModerationCategories == null) + { + return null; + } + return BinaryContent.Create(internalModerationCategories, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModerationCategories(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModerationCategories(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModerationCategories.cs b/src/Generated/Models/InternalModerationCategories.cs index e74bb32c0..a904d46e9 100644 --- a/src/Generated/Models/InternalModerationCategories.cs +++ b/src/Generated/Models/InternalModerationCategories.cs @@ -9,7 +9,8 @@ namespace OpenAI.Moderations { internal partial class InternalModerationCategories { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, bool illicit, bool illicitViolent, bool selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic) { Hate = hate; @@ -27,7 +28,7 @@ internal InternalModerationCategories(bool hate, bool hateThreatening, bool hara ViolenceGraphic = violenceGraphic; } - internal InternalModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, bool illicit, bool illicitViolent, bool selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic, IDictionary serializedAdditionalRawData) + internal InternalModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, bool illicit, bool illicitViolent, bool selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic, IDictionary additionalBinaryDataProperties) { Hate = hate; HateThreatening = hateThreatening; @@ -42,25 +43,39 @@ internal InternalModerationCategories(bool hate, bool hateThreatening, bool hara SexualMinors = sexualMinors; Violence = violence; ViolenceGraphic = violenceGraphic; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalModerationCategories() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public bool Hate { get; } + public bool HateThreatening { get; } + public bool Harassment { get; } + public bool HarassmentThreatening { get; } + public bool Illicit { get; } + public bool IllicitViolent { get; } + public bool SelfHarm { get; } + public bool SelfHarmIntent { get; } + public bool SelfHarmInstructions { get; } + public bool Sexual { get; } + public bool SexualMinors { get; } + public bool Violence { get; } + public bool ViolenceGraphic { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs b/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs index 89f8e1ab7..5ce3e2fbd 100644 --- a/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs +++ b/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs @@ -7,88 +7,98 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { internal partial class InternalModerationCategoryScores : IJsonModel { + internal InternalModerationCategoryScores() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModerationCategoryScores)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("hate") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate") != true) { writer.WritePropertyName("hate"u8); writer.WriteNumberValue(Hate); } - if (SerializedAdditionalRawData?.ContainsKey("hate/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("hate/threatening") != true) { writer.WritePropertyName("hate/threatening"u8); writer.WriteNumberValue(HateThreatening); } - if (SerializedAdditionalRawData?.ContainsKey("harassment") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment") != true) { writer.WritePropertyName("harassment"u8); writer.WriteNumberValue(Harassment); } - if (SerializedAdditionalRawData?.ContainsKey("harassment/threatening") != true) + if (_additionalBinaryDataProperties?.ContainsKey("harassment/threatening") != true) { writer.WritePropertyName("harassment/threatening"u8); writer.WriteNumberValue(HarassmentThreatening); } - if (SerializedAdditionalRawData?.ContainsKey("illicit") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit") != true) { writer.WritePropertyName("illicit"u8); writer.WriteNumberValue(Illicit); } - if (SerializedAdditionalRawData?.ContainsKey("illicit/violent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("illicit/violent") != true) { writer.WritePropertyName("illicit/violent"u8); writer.WriteNumberValue(IllicitViolent); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm") != true) { writer.WritePropertyName("self-harm"u8); writer.WriteNumberValue(SelfHarm); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/intent") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/intent") != true) { writer.WritePropertyName("self-harm/intent"u8); writer.WriteNumberValue(SelfHarmIntent); } - if (SerializedAdditionalRawData?.ContainsKey("self-harm/instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("self-harm/instructions") != true) { writer.WritePropertyName("self-harm/instructions"u8); writer.WriteNumberValue(SelfHarmInstructions); } - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual") != true) { writer.WritePropertyName("sexual"u8); writer.WriteNumberValue(Sexual); } - if (SerializedAdditionalRawData?.ContainsKey("sexual/minors") != true) + if (_additionalBinaryDataProperties?.ContainsKey("sexual/minors") != true) { writer.WritePropertyName("sexual/minors"u8); writer.WriteNumberValue(SexualMinors); } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence") != true) { writer.WritePropertyName("violence"u8); writer.WriteNumberValue(Violence); } - if (SerializedAdditionalRawData?.ContainsKey("violence/graphic") != true) + if (_additionalBinaryDataProperties?.ContainsKey("violence/graphic") != true) { writer.WritePropertyName("violence/graphic"u8); writer.WriteNumberValue(ViolenceGraphic); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -96,7 +106,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -105,25 +115,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalModerationCategoryScores IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModerationCategoryScores IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModerationCategoryScores JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModerationCategoryScores)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModerationCategoryScores(document.RootElement, options); } - internal static InternalModerationCategoryScores DeserializeInternalModerationCategoryScores(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModerationCategoryScores DeserializeInternalModerationCategoryScores(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -141,82 +149,79 @@ internal static InternalModerationCategoryScores DeserializeInternalModerationCa float sexualMinors = default; float violence = default; float violenceGraphic = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("hate"u8)) + if (prop.NameEquals("hate"u8)) { - hate = property.Value.GetSingle(); + hate = prop.Value.GetSingle(); continue; } - if (property.NameEquals("hate/threatening"u8)) + if (prop.NameEquals("hate/threatening"u8)) { - hateThreatening = property.Value.GetSingle(); + hateThreatening = prop.Value.GetSingle(); continue; } - if (property.NameEquals("harassment"u8)) + if (prop.NameEquals("harassment"u8)) { - harassment = property.Value.GetSingle(); + harassment = prop.Value.GetSingle(); continue; } - if (property.NameEquals("harassment/threatening"u8)) + if (prop.NameEquals("harassment/threatening"u8)) { - harassmentThreatening = property.Value.GetSingle(); + harassmentThreatening = prop.Value.GetSingle(); continue; } - if (property.NameEquals("illicit"u8)) + if (prop.NameEquals("illicit"u8)) { - illicit = property.Value.GetSingle(); + illicit = prop.Value.GetSingle(); continue; } - if (property.NameEquals("illicit/violent"u8)) + if (prop.NameEquals("illicit/violent"u8)) { - illicitViolent = property.Value.GetSingle(); + illicitViolent = prop.Value.GetSingle(); continue; } - if (property.NameEquals("self-harm"u8)) + if (prop.NameEquals("self-harm"u8)) { - selfHarm = property.Value.GetSingle(); + selfHarm = prop.Value.GetSingle(); continue; } - if (property.NameEquals("self-harm/intent"u8)) + if (prop.NameEquals("self-harm/intent"u8)) { - selfHarmIntent = property.Value.GetSingle(); + selfHarmIntent = prop.Value.GetSingle(); continue; } - if (property.NameEquals("self-harm/instructions"u8)) + if (prop.NameEquals("self-harm/instructions"u8)) { - selfHarmInstructions = property.Value.GetSingle(); + selfHarmInstructions = prop.Value.GetSingle(); continue; } - if (property.NameEquals("sexual"u8)) + if (prop.NameEquals("sexual"u8)) { - sexual = property.Value.GetSingle(); + sexual = prop.Value.GetSingle(); continue; } - if (property.NameEquals("sexual/minors"u8)) + if (prop.NameEquals("sexual/minors"u8)) { - sexualMinors = property.Value.GetSingle(); + sexualMinors = prop.Value.GetSingle(); continue; } - if (property.NameEquals("violence"u8)) + if (prop.NameEquals("violence"u8)) { - violence = property.Value.GetSingle(); + violence = prop.Value.GetSingle(); continue; } - if (property.NameEquals("violence/graphic"u8)) + if (prop.NameEquals("violence/graphic"u8)) { - violenceGraphic = property.Value.GetSingle(); + violenceGraphic = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalModerationCategoryScores( hate, hateThreatening, @@ -231,13 +236,14 @@ internal static InternalModerationCategoryScores DeserializeInternalModerationCa sexualMinors, violence, violenceGraphic, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -247,15 +253,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalModerationCategoryScores IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModerationCategoryScores IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModerationCategoryScores 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModerationCategoryScores(document.RootElement, options); } default: @@ -265,15 +272,20 @@ InternalModerationCategoryScores IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModerationCategoryScores FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModerationCategoryScores internalModerationCategoryScores) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModerationCategoryScores(document.RootElement); + if (internalModerationCategoryScores == null) + { + return null; + } + return BinaryContent.Create(internalModerationCategoryScores, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModerationCategoryScores(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModerationCategoryScores(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModerationCategoryScores.cs b/src/Generated/Models/InternalModerationCategoryScores.cs index ea45180d1..b1b5c1ff7 100644 --- a/src/Generated/Models/InternalModerationCategoryScores.cs +++ b/src/Generated/Models/InternalModerationCategoryScores.cs @@ -9,7 +9,8 @@ namespace OpenAI.Moderations { internal partial class InternalModerationCategoryScores { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, float illicit, float illicitViolent, float selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic) { Hate = hate; @@ -27,7 +28,7 @@ internal InternalModerationCategoryScores(float hate, float hateThreatening, flo ViolenceGraphic = violenceGraphic; } - internal InternalModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, float illicit, float illicitViolent, float selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic, IDictionary serializedAdditionalRawData) + internal InternalModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, float illicit, float illicitViolent, float selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic, IDictionary additionalBinaryDataProperties) { Hate = hate; HateThreatening = hateThreatening; @@ -42,25 +43,39 @@ internal InternalModerationCategoryScores(float hate, float hateThreatening, flo SexualMinors = sexualMinors; Violence = violence; ViolenceGraphic = violenceGraphic; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalModerationCategoryScores() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public float Hate { get; } + public float HateThreatening { get; } + public float Harassment { get; } + public float HarassmentThreatening { get; } + public float Illicit { get; } + public float IllicitViolent { get; } + public float SelfHarm { get; } + public float SelfHarmIntent { get; } + public float SelfHarmInstructions { get; } + public float Sexual { get; } + public float SexualMinors { get; } + public float Violence { get; } + public float ViolenceGraphic { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs b/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs index bb4a89610..b720134bc 100644 --- a/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs +++ b/src/Generated/Models/InternalModifyAssistantRequestToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalModifyAssistantRequestToolResources : IJsonModel< { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModifyAssistantRequestToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWrite #endif } } - writer.WriteEndObject(); } - InternalModifyAssistantRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModifyAssistantRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModifyAssistantRequestToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModifyAssistantRequestToolResources(document.RootElement, options); } - internal static InternalModifyAssistantRequestToolResources DeserializeInternalModifyAssistantRequestToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModifyAssistantRequestToolResources DeserializeInternalModifyAssistantRequestToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter = default; InternalToolResourcesFileSearchIdsOnly fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalModifyAssistantRequestToolResourcesCodeInterpreter.DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalModifyAssistantRequestToolResourcesCodeInterpreter.DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyAssistantRequestToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalModifyAssistantRequestToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write( } } - InternalModifyAssistantRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModifyAssistantRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModifyAssistantRequestToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModifyAssistantRequestToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalModifyAssistantRequestToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyAssistantRequestToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModifyAssistantRequestToolResources internalModifyAssistantRequestToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyAssistantRequestToolResources(document.RootElement); + if (internalModifyAssistantRequestToolResources == null) + { + return null; + } + return BinaryContent.Create(internalModifyAssistantRequestToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModifyAssistantRequestToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModifyAssistantRequestToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs b/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs index 3bcf4c24d..661400bd6 100644 --- a/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs +++ b/src/Generated/Models/InternalModifyAssistantRequestToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalModifyAssistantRequestToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalModifyAssistantRequestToolResources() { } - internal InternalModifyAssistantRequestToolResources(InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) + internal InternalModifyAssistantRequestToolResources(InternalModifyAssistantRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalModifyAssistantRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.Serialization.cs index 2b3ea1d6a..88bfe2b56 100644 --- a/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalModifyAssistantRequestToolResourcesCodeInterprete { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModifyAssistantRequestToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Writ #endif } } - writer.WriteEndObject(); } - InternalModifyAssistantRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModifyAssistantRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModifyAssistantRequestToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModifyAssistantRequestToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalModifyAssistantRequestToolResourcesCodeInterpreter DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModifyAssistantRequestToolResourcesCodeInterpreter DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyAssistantRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalModifyAssistantRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModifyAssistantRequestToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModifyAssistantRequestToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalModifyAssistantRequestToolResourcesCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyAssistantRequestToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModifyAssistantRequestToolResourcesCodeInterpreter internalModifyAssistantRequestToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(document.RootElement); + if (internalModifyAssistantRequestToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalModifyAssistantRequestToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModifyAssistantRequestToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModifyAssistantRequestToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.cs index 1b2538796..76eac7d76 100644 --- a/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalModifyAssistantRequestToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalModifyAssistantRequestToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalModifyAssistantRequestToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalModifyAssistantRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary serializedAdditionalRawData) + internal InternalModifyAssistantRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs b/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs index 3354accf3..736a11320 100644 --- a/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs +++ b/src/Generated/Models/InternalModifyThreadRequestToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalModifyThreadRequestToolResources : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModifyThreadRequestToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter w } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWriter w #endif } } - writer.WriteEndObject(); } - InternalModifyThreadRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModifyThreadRequestToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModifyThreadRequestToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModifyThreadRequestToolResources(document.RootElement, options); } - internal static InternalModifyThreadRequestToolResources DeserializeInternalModifyThreadRequestToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModifyThreadRequestToolResources DeserializeInternalModifyThreadRequestToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter = default; InternalToolResourcesFileSearchIdsOnly fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalModifyThreadRequestToolResourcesCodeInterpreter.DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalModifyThreadRequestToolResourcesCodeInterpreter.DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(property.Value, options); + fileSearch = InternalToolResourcesFileSearchIdsOnly.DeserializeInternalToolResourcesFileSearchIdsOnly(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyThreadRequestToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalModifyThreadRequestToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalModifyThreadRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModifyThreadRequestToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModifyThreadRequestToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModifyThreadRequestToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalModifyThreadRequestToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyThreadRequestToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModifyThreadRequestToolResources internalModifyThreadRequestToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyThreadRequestToolResources(document.RootElement); + if (internalModifyThreadRequestToolResources == null) + { + return null; + } + return BinaryContent.Create(internalModifyThreadRequestToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModifyThreadRequestToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModifyThreadRequestToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModifyThreadRequestToolResources.cs b/src/Generated/Models/InternalModifyThreadRequestToolResources.cs index 0876ba2de..9a84e3744 100644 --- a/src/Generated/Models/InternalModifyThreadRequestToolResources.cs +++ b/src/Generated/Models/InternalModifyThreadRequestToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalModifyThreadRequestToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalModifyThreadRequestToolResources() { } - internal InternalModifyThreadRequestToolResources(InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary serializedAdditionalRawData) + internal InternalModifyThreadRequestToolResources(InternalModifyThreadRequestToolResourcesCodeInterpreter codeInterpreter, InternalToolResourcesFileSearchIdsOnly fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalModifyThreadRequestToolResourcesCodeInterpreter CodeInterpreter { get; set; } + public InternalToolResourcesFileSearchIdsOnly FileSearch { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.Serialization.cs index cc3aafd77..43462682f 100644 --- a/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalModifyThreadRequestToolResourcesCodeInterpreter : { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalModifyThreadRequestToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(U } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(U #endif } } - writer.WriteEndObject(); } - InternalModifyThreadRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModifyThreadRequestToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalModifyThreadRequestToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalModifyThreadRequestToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalModifyThreadRequestToolResourcesCodeInterpreter DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModifyThreadRequestToolResourcesCodeInterpreter DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalModifyThreadRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalModifyThreadRequestToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalModifyThreadRequestToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalModifyThreadRequestToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalModifyThreadRequestToolResourcesCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalModifyThreadRequestToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalModifyThreadRequestToolResourcesCodeInterpreter internalModifyThreadRequestToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(document.RootElement); + if (internalModifyThreadRequestToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalModifyThreadRequestToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalModifyThreadRequestToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalModifyThreadRequestToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.cs index df0ce6bf8..6946e8662 100644 --- a/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalModifyThreadRequestToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalModifyThreadRequestToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalModifyThreadRequestToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalModifyThreadRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary serializedAdditionalRawData) + internal InternalModifyThreadRequestToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs b/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs index 6ccf09de3..b2cdc55e3 100644 --- a/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs +++ b/src/Generated/Models/InternalOmniTypedResponseFormat.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { [PersistableModelProxy(typeof(InternalUnknownOmniTypedResponseFormat))] - internal partial class InternalOmniTypedResponseFormat : IJsonModel + internal abstract partial class InternalOmniTypedResponseFormat : IJsonModel { + internal InternalOmniTypedResponseFormat() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalOmniTypedResponseFormat)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,45 +55,47 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalOmniTypedResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); } - internal static InternalOmniTypedResponseFormat DeserializeInternalOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalOmniTypedResponseFormat DeserializeInternalOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "json_object": return InternalResponseFormatJsonObject.DeserializeInternalResponseFormatJsonObject(element, options); - case "json_schema": return InternalResponseFormatJsonSchema.DeserializeInternalResponseFormatJsonSchema(element, options); - case "text": return InternalResponseFormatText.DeserializeInternalResponseFormatText(element, options); + case "text": + return InternalResponseFormatText.DeserializeInternalResponseFormatText(element, options); + case "json_object": + return InternalResponseFormatJsonObject.DeserializeInternalResponseFormatJsonObject(element, options); + case "json_schema": + return InternalResponseFormatJsonSchema.DeserializeInternalResponseFormatJsonSchema(element, options); } } return InternalUnknownOmniTypedResponseFormat.DeserializeInternalUnknownOmniTypedResponseFormat(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -93,15 +105,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalOmniTypedResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); } default: @@ -111,15 +124,20 @@ InternalOmniTypedResponseFormat IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalOmniTypedResponseFormat FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalOmniTypedResponseFormat internalOmniTypedResponseFormat) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalOmniTypedResponseFormat(document.RootElement); + if (internalOmniTypedResponseFormat == null) + { + return null; + } + return BinaryContent.Create(internalOmniTypedResponseFormat, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalOmniTypedResponseFormat(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalOmniTypedResponseFormat(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalOmniTypedResponseFormat.cs b/src/Generated/Models/InternalOmniTypedResponseFormat.cs index da255f506..5415880b5 100644 --- a/src/Generated/Models/InternalOmniTypedResponseFormat.cs +++ b/src/Generated/Models/InternalOmniTypedResponseFormat.cs @@ -9,17 +9,25 @@ namespace OpenAI.Internal { internal abstract partial class InternalOmniTypedResponseFormat { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalOmniTypedResponseFormat() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalOmniTypedResponseFormat(string @type) { + Type = @type; } - internal InternalOmniTypedResponseFormat(string type, IDictionary serializedAdditionalRawData) + internal InternalOmniTypedResponseFormat(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalOpenAIFileObject.cs b/src/Generated/Models/InternalOpenAIFileObject.cs index d32ba1770..4d201bd7b 100644 --- a/src/Generated/Models/InternalOpenAIFileObject.cs +++ b/src/Generated/Models/InternalOpenAIFileObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalOpenAIFileObject : IEquatable { private readonly string _value; + private const string FileValue = "file"; public InternalOpenAIFileObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FileValue = "file"; + _value = value; + } public static InternalOpenAIFileObject File { get; } = new InternalOpenAIFileObject(FileValue); + public static bool operator ==(InternalOpenAIFileObject left, InternalOpenAIFileObject right) => left.Equals(right); + public static bool operator !=(InternalOpenAIFileObject left, InternalOpenAIFileObject right) => !left.Equals(right); + public static implicit operator InternalOpenAIFileObject(string value) => new InternalOpenAIFileObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalOpenAIFileObject other && Equals(other); + public bool Equals(InternalOpenAIFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeClientEvent.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEvent.Serialization.cs index 6fd0daa7e..46b19f866 100644 --- a/src/Generated/Models/InternalRealtimeClientEvent.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEvent.Serialization.cs @@ -6,34 +6,44 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeClientEvent))] - internal partial class InternalRealtimeClientEvent : IJsonModel + internal abstract partial class InternalRealtimeClientEvent : IJsonModel { + internal InternalRealtimeClientEvent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEvent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Kind.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) + if (Optional.IsDefined(EventId) && _additionalBinaryDataProperties?.ContainsKey("event_id") != true) { writer.WritePropertyName("event_id"u8); writer.WriteStringValue(EventId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,51 +60,59 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - InternalRealtimeClientEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEvent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEvent(document.RootElement, options); } - internal static InternalRealtimeClientEvent DeserializeInternalRealtimeClientEvent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEvent DeserializeInternalRealtimeClientEvent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "conversation.item.create": return InternalRealtimeClientEventConversationItemCreate.DeserializeInternalRealtimeClientEventConversationItemCreate(element, options); - case "conversation.item.delete": return InternalRealtimeClientEventConversationItemDelete.DeserializeInternalRealtimeClientEventConversationItemDelete(element, options); - case "conversation.item.truncate": return InternalRealtimeClientEventConversationItemTruncate.DeserializeInternalRealtimeClientEventConversationItemTruncate(element, options); - case "input_audio_buffer.append": return InternalRealtimeClientEventInputAudioBufferAppend.DeserializeInternalRealtimeClientEventInputAudioBufferAppend(element, options); - case "input_audio_buffer.clear": return InternalRealtimeClientEventInputAudioBufferClear.DeserializeInternalRealtimeClientEventInputAudioBufferClear(element, options); - case "input_audio_buffer.commit": return InternalRealtimeClientEventInputAudioBufferCommit.DeserializeInternalRealtimeClientEventInputAudioBufferCommit(element, options); - case "response.cancel": return InternalRealtimeClientEventResponseCancel.DeserializeInternalRealtimeClientEventResponseCancel(element, options); - case "response.create": return InternalRealtimeClientEventResponseCreate.DeserializeInternalRealtimeClientEventResponseCreate(element, options); - case "session.update": return InternalRealtimeClientEventSessionUpdate.DeserializeInternalRealtimeClientEventSessionUpdate(element, options); + case "session.update": + return InternalRealtimeClientEventSessionUpdate.DeserializeInternalRealtimeClientEventSessionUpdate(element, options); + case "input_audio_buffer.append": + return InternalRealtimeClientEventInputAudioBufferAppend.DeserializeInternalRealtimeClientEventInputAudioBufferAppend(element, options); + case "input_audio_buffer.commit": + return InternalRealtimeClientEventInputAudioBufferCommit.DeserializeInternalRealtimeClientEventInputAudioBufferCommit(element, options); + case "input_audio_buffer.clear": + return InternalRealtimeClientEventInputAudioBufferClear.DeserializeInternalRealtimeClientEventInputAudioBufferClear(element, options); + case "conversation.item.create": + return InternalRealtimeClientEventConversationItemCreate.DeserializeInternalRealtimeClientEventConversationItemCreate(element, options); + case "conversation.item.truncate": + return InternalRealtimeClientEventConversationItemTruncate.DeserializeInternalRealtimeClientEventConversationItemTruncate(element, options); + case "conversation.item.delete": + return InternalRealtimeClientEventConversationItemDelete.DeserializeInternalRealtimeClientEventConversationItemDelete(element, options); + case "response.create": + return InternalRealtimeClientEventResponseCreate.DeserializeInternalRealtimeClientEventResponseCreate(element, options); + case "response.cancel": + return InternalRealtimeClientEventResponseCancel.DeserializeInternalRealtimeClientEventResponseCancel(element, options); } } return UnknownRealtimeClientEvent.DeserializeUnknownRealtimeClientEvent(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -104,15 +122,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalRealtimeClientEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEvent(document.RootElement, options); } default: @@ -122,15 +141,20 @@ InternalRealtimeClientEvent IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeClientEvent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEvent internalRealtimeClientEvent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEvent(document.RootElement); + if (internalRealtimeClientEvent == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEvent, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEvent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEvent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEvent.cs b/src/Generated/Models/InternalRealtimeClientEvent.cs index f3696c8a1..0b986d83d 100644 --- a/src/Generated/Models/InternalRealtimeClientEvent.cs +++ b/src/Generated/Models/InternalRealtimeClientEvent.cs @@ -9,19 +9,28 @@ namespace OpenAI.RealtimeConversation { internal abstract partial class InternalRealtimeClientEvent { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalRealtimeClientEvent() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalRealtimeClientEvent(InternalRealtimeClientEventType kind) { + Kind = kind; } - internal InternalRealtimeClientEvent(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData) + internal InternalRealtimeClientEvent(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties) { Kind = kind; EventId = eventId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal InternalRealtimeClientEventType Kind { get; set; } + public string EventId { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.Serialization.cs index 58f889004..e3572ee2e 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemCreate : IJsonModel { + internal InternalRealtimeClientEventConversationItemCreate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventConversationItemCreate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("previous_item_id") != true && Optional.IsDefined(PreviousItemId)) + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(PreviousItemId) && _additionalBinaryDataProperties?.ContainsKey("previous_item_id") != true) { writer.WritePropertyName("previous_item_id"u8); writer.WriteStringValue(PreviousItemId); } - if (SerializedAdditionalRawData?.ContainsKey("item") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item") != true) { writer.WritePropertyName("item"u8); writer.WriteObjectValue(Item, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventConversationItemCreate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventConversationItemCreate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemCreate)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventConversationItemCreate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventConversationItemCreate(document.RootElement, options); } - internal static InternalRealtimeClientEventConversationItemCreate DeserializeInternalRealtimeClientEventConversationItemCreate(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventConversationItemCreate DeserializeInternalRealtimeClientEventConversationItemCreate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalRealtimeClientEventType kind = default; + string eventId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string previousItemId = default; ConversationItem item = default; - InternalRealtimeClientEventType type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("previous_item_id"u8)) + if (prop.NameEquals("type"u8)) { - previousItemId = property.Value.GetString(); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("item"u8)) + if (prop.NameEquals("event_id"u8)) { - item = ConversationItem.DeserializeConversationItem(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("previous_item_id"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + previousItemId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item"u8)) { - eventId = property.Value.GetString(); + item = ConversationItem.DeserializeConversationItem(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventConversationItemCreate(type, eventId, serializedAdditionalRawData, previousItemId, item); + return new InternalRealtimeClientEventConversationItemCreate(kind, eventId, additionalBinaryDataProperties, previousItemId, item); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel. } } - InternalRealtimeClientEventConversationItemCreate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventConversationItemCreate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemCreate)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventConversationItemCreate(document.RootElement, options); } default: @@ -152,15 +131,20 @@ InternalRealtimeClientEventConversationItemCreate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventConversationItemCreate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventConversationItemCreate internalRealtimeClientEventConversationItemCreate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventConversationItemCreate(document.RootElement); + if (internalRealtimeClientEventConversationItemCreate == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventConversationItemCreate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventConversationItemCreate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventConversationItemCreate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.cs index 7215a58ba..22c21466f 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemCreate.cs @@ -4,30 +4,27 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemCreate : InternalRealtimeClientEvent { - public InternalRealtimeClientEventConversationItemCreate(ConversationItem item) + public InternalRealtimeClientEventConversationItemCreate(ConversationItem item) : base(InternalRealtimeClientEventType.ConversationItemCreate) { Argument.AssertNotNull(item, nameof(item)); - Kind = InternalRealtimeClientEventType.ConversationItemCreate; Item = item; } - internal InternalRealtimeClientEventConversationItemCreate(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, string previousItemId, ConversationItem item) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventConversationItemCreate(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, string previousItemId, ConversationItem item) : base(kind, eventId, additionalBinaryDataProperties) { PreviousItemId = previousItemId; Item = item; } - internal InternalRealtimeClientEventConversationItemCreate() - { - } - public string PreviousItemId { get; set; } + public ConversationItem Item { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.Serialization.cs index 17eea40a5..ebe414f6f 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemDelete : IJsonModel { + internal InternalRealtimeClientEventConversationItemDelete() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventConversationItemDelete)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventConversationItemDelete IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventConversationItemDelete IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemDelete)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventConversationItemDelete)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventConversationItemDelete(document.RootElement, options); } - internal static InternalRealtimeClientEventConversationItemDelete DeserializeInternalRealtimeClientEventConversationItemDelete(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventConversationItemDelete DeserializeInternalRealtimeClientEventConversationItemDelete(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string itemId = default; - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string itemId = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("item_id"u8)) { - eventId = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventConversationItemDelete(type, eventId, serializedAdditionalRawData, itemId); + return new InternalRealtimeClientEventConversationItemDelete(kind, eventId, additionalBinaryDataProperties, itemId); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel. } } - InternalRealtimeClientEventConversationItemDelete IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventConversationItemDelete IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemDelete)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventConversationItemDelete(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRealtimeClientEventConversationItemDelete IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventConversationItemDelete FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventConversationItemDelete internalRealtimeClientEventConversationItemDelete) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventConversationItemDelete(document.RootElement); + if (internalRealtimeClientEventConversationItemDelete == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventConversationItemDelete, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventConversationItemDelete(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventConversationItemDelete(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.cs index 4a446bda4..a0db8bcba 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemDelete.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemDelete : InternalRealtimeClientEvent { - public InternalRealtimeClientEventConversationItemDelete(string itemId) + public InternalRealtimeClientEventConversationItemDelete(string itemId) : base(InternalRealtimeClientEventType.ConversationItemDelete) { Argument.AssertNotNull(itemId, nameof(itemId)); - Kind = InternalRealtimeClientEventType.ConversationItemDelete; ItemId = itemId; } - internal InternalRealtimeClientEventConversationItemDelete(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, string itemId) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventConversationItemDelete(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, string itemId) : base(kind, eventId, additionalBinaryDataProperties) { ItemId = itemId; } - internal InternalRealtimeClientEventConversationItemDelete() - { - } - public string ItemId { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.Serialization.cs index 082cc9699..da934231d 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.Serialization.cs @@ -7,141 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemTruncate : IJsonModel { + internal InternalRealtimeClientEventConversationItemTruncate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventConversationItemTruncate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("audio_end_ms") != true) + if (_additionalBinaryDataProperties?.ContainsKey("audio_end_ms") != true) { writer.WritePropertyName("audio_end_ms"u8); writer.WriteNumberValue(AudioEndMs); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventConversationItemTruncate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventConversationItemTruncate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemTruncate)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventConversationItemTruncate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventConversationItemTruncate(document.RootElement, options); } - internal static InternalRealtimeClientEventConversationItemTruncate DeserializeInternalRealtimeClientEventConversationItemTruncate(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventConversationItemTruncate DeserializeInternalRealtimeClientEventConversationItemTruncate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalRealtimeClientEventType kind = default; + string eventId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string itemId = default; int contentIndex = default; int audioEndMs = default; - InternalRealtimeClientEventType type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("event_id"u8)) { - contentIndex = property.Value.GetInt32(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("audio_end_ms"u8)) + if (prop.NameEquals("item_id"u8)) { - audioEndMs = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("audio_end_ms"u8)) { - eventId = property.Value.GetString(); + audioEndMs = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeClientEventConversationItemTruncate( - type, + kind, eventId, - serializedAdditionalRawData, + additionalBinaryDataProperties, itemId, contentIndex, audioEndMs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +129,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventConversationItemTruncate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventConversationItemTruncate)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventConversationItemTruncate(document.RootElement, options); } default: @@ -169,15 +148,20 @@ InternalRealtimeClientEventConversationItemTruncate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventConversationItemTruncate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventConversationItemTruncate internalRealtimeClientEventConversationItemTruncate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventConversationItemTruncate(document.RootElement); + if (internalRealtimeClientEventConversationItemTruncate == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventConversationItemTruncate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventConversationItemTruncate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventConversationItemTruncate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.cs b/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.cs index d69ec334b..89f7e749a 100644 --- a/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.cs +++ b/src/Generated/Models/InternalRealtimeClientEventConversationItemTruncate.cs @@ -4,34 +4,32 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventConversationItemTruncate : InternalRealtimeClientEvent { - public InternalRealtimeClientEventConversationItemTruncate(string itemId, int contentIndex, int audioEndMs) + public InternalRealtimeClientEventConversationItemTruncate(string itemId, int contentIndex, int audioEndMs) : base(InternalRealtimeClientEventType.ConversationItemTruncate) { Argument.AssertNotNull(itemId, nameof(itemId)); - Kind = InternalRealtimeClientEventType.ConversationItemTruncate; ItemId = itemId; ContentIndex = contentIndex; AudioEndMs = audioEndMs; } - internal InternalRealtimeClientEventConversationItemTruncate(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, string itemId, int contentIndex, int audioEndMs) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventConversationItemTruncate(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, string itemId, int contentIndex, int audioEndMs) : base(kind, eventId, additionalBinaryDataProperties) { ItemId = itemId; ContentIndex = contentIndex; AudioEndMs = audioEndMs; } - internal InternalRealtimeClientEventConversationItemTruncate() - { - } - public string ItemId { get; } + public int ContentIndex { get; } + public int AudioEndMs { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.Serialization.cs index 55ef0ecc1..de235c643 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventInputAudioBufferAppend : IJsonModel { + internal InternalRealtimeClientEventInputAudioBufferAppend() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventInputAudioBufferAppend)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("audio") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("audio") != true) { writer.WritePropertyName("audio"u8); writer.WriteBase64StringValue(Audio.ToArray(), "D"); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventInputAudioBufferAppend IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventInputAudioBufferAppend IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferAppend)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventInputAudioBufferAppend)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventInputAudioBufferAppend(document.RootElement, options); } - internal static InternalRealtimeClientEventInputAudioBufferAppend DeserializeInternalRealtimeClientEventInputAudioBufferAppend(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventInputAudioBufferAppend DeserializeInternalRealtimeClientEventInputAudioBufferAppend(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - BinaryData audio = default; - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + BinaryData audio = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("audio"u8)) + if (prop.NameEquals("type"u8)) { - audio = BinaryData.FromBytes(property.Value.GetBytesFromBase64("D")); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("audio"u8)) { - eventId = property.Value.GetString(); + audio = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventInputAudioBufferAppend(type, eventId, serializedAdditionalRawData, audio); + return new InternalRealtimeClientEventInputAudioBufferAppend(kind, eventId, additionalBinaryDataProperties, audio); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel. } } - InternalRealtimeClientEventInputAudioBufferAppend IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventInputAudioBufferAppend IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferAppend)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventInputAudioBufferAppend(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRealtimeClientEventInputAudioBufferAppend IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventInputAudioBufferAppend FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventInputAudioBufferAppend internalRealtimeClientEventInputAudioBufferAppend) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventInputAudioBufferAppend(document.RootElement); + if (internalRealtimeClientEventInputAudioBufferAppend == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventInputAudioBufferAppend, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventInputAudioBufferAppend(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventInputAudioBufferAppend(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.cs index 908a3010d..0dab151c5 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferAppend.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventInputAudioBufferAppend : InternalRealtimeClientEvent { - public InternalRealtimeClientEventInputAudioBufferAppend(BinaryData audio) + public InternalRealtimeClientEventInputAudioBufferAppend(BinaryData audio) : base(InternalRealtimeClientEventType.InputAudioBufferAppend) { Argument.AssertNotNull(audio, nameof(audio)); - Kind = InternalRealtimeClientEventType.InputAudioBufferAppend; Audio = audio; } - internal InternalRealtimeClientEventInputAudioBufferAppend(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, BinaryData audio) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventInputAudioBufferAppend(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, BinaryData audio) : base(kind, eventId, additionalBinaryDataProperties) { Audio = audio; } - internal InternalRealtimeClientEventInputAudioBufferAppend() - { - } - public BinaryData Audio { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.Serialization.cs index b40fd35bb..7819cd1c2 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,95 +15,68 @@ internal partial class InternalRealtimeClientEventInputAudioBufferClear : IJsonM { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventInputAudioBufferClear)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeClientEventInputAudioBufferClear IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventInputAudioBufferClear IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferClear)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventInputAudioBufferClear)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventInputAudioBufferClear(document.RootElement, options); } - internal static InternalRealtimeClientEventInputAudioBufferClear DeserializeInternalRealtimeClientEventInputAudioBufferClear(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventInputAudioBufferClear DeserializeInternalRealtimeClientEventInputAudioBufferClear(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("event_id"u8)) { - eventId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventInputAudioBufferClear(type, eventId, serializedAdditionalRawData); + return new InternalRealtimeClientEventInputAudioBufferClear(kind, eventId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +86,16 @@ BinaryData IPersistableModel.W } } - InternalRealtimeClientEventInputAudioBufferClear IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventInputAudioBufferClear IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferClear)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventInputAudioBufferClear(document.RootElement, options); } default: @@ -130,15 +105,20 @@ InternalRealtimeClientEventInputAudioBufferClear IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventInputAudioBufferClear FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventInputAudioBufferClear internalRealtimeClientEventInputAudioBufferClear) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventInputAudioBufferClear(document.RootElement); + if (internalRealtimeClientEventInputAudioBufferClear == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventInputAudioBufferClear, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventInputAudioBufferClear(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventInputAudioBufferClear(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.cs index f1012e175..0838f1d6f 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferClear.cs @@ -9,12 +9,11 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventInputAudioBufferClear : InternalRealtimeClientEvent { - public InternalRealtimeClientEventInputAudioBufferClear() + public InternalRealtimeClientEventInputAudioBufferClear() : base(InternalRealtimeClientEventType.InputAudioBufferClear) { - Kind = InternalRealtimeClientEventType.InputAudioBufferClear; } - internal InternalRealtimeClientEventInputAudioBufferClear(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventInputAudioBufferClear(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties) : base(kind, eventId, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.Serialization.cs index 6466a1da1..7d1f686e3 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,95 +15,68 @@ internal partial class InternalRealtimeClientEventInputAudioBufferCommit : IJson { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventInputAudioBufferCommit)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeClientEventInputAudioBufferCommit IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventInputAudioBufferCommit IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferCommit)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventInputAudioBufferCommit)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventInputAudioBufferCommit(document.RootElement, options); } - internal static InternalRealtimeClientEventInputAudioBufferCommit DeserializeInternalRealtimeClientEventInputAudioBufferCommit(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventInputAudioBufferCommit DeserializeInternalRealtimeClientEventInputAudioBufferCommit(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("event_id"u8)) { - eventId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventInputAudioBufferCommit(type, eventId, serializedAdditionalRawData); + return new InternalRealtimeClientEventInputAudioBufferCommit(kind, eventId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +86,16 @@ BinaryData IPersistableModel. } } - InternalRealtimeClientEventInputAudioBufferCommit IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventInputAudioBufferCommit IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventInputAudioBufferCommit)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventInputAudioBufferCommit(document.RootElement, options); } default: @@ -130,15 +105,20 @@ InternalRealtimeClientEventInputAudioBufferCommit IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventInputAudioBufferCommit FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventInputAudioBufferCommit internalRealtimeClientEventInputAudioBufferCommit) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventInputAudioBufferCommit(document.RootElement); + if (internalRealtimeClientEventInputAudioBufferCommit == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventInputAudioBufferCommit, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventInputAudioBufferCommit(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventInputAudioBufferCommit(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.cs b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.cs index 5cf2fe381..5e13b96b1 100644 --- a/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.cs +++ b/src/Generated/Models/InternalRealtimeClientEventInputAudioBufferCommit.cs @@ -9,12 +9,11 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventInputAudioBufferCommit : InternalRealtimeClientEvent { - public InternalRealtimeClientEventInputAudioBufferCommit() + public InternalRealtimeClientEventInputAudioBufferCommit() : base(InternalRealtimeClientEventType.InputAudioBufferCommit) { - Kind = InternalRealtimeClientEventType.InputAudioBufferCommit; } - internal InternalRealtimeClientEventInputAudioBufferCommit(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventInputAudioBufferCommit(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties) : base(kind, eventId, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCancel.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCancel.Serialization.cs index 1aeb18e83..6da7ef02c 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCancel.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCancel.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,95 +15,68 @@ internal partial class InternalRealtimeClientEventResponseCancel : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventResponseCancel)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeClientEventResponseCancel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventResponseCancel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventResponseCancel)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventResponseCancel)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventResponseCancel(document.RootElement, options); } - internal static InternalRealtimeClientEventResponseCancel DeserializeInternalRealtimeClientEventResponseCancel(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventResponseCancel DeserializeInternalRealtimeClientEventResponseCancel(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("event_id"u8)) { - eventId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventResponseCancel(type, eventId, serializedAdditionalRawData); + return new InternalRealtimeClientEventResponseCancel(kind, eventId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +86,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalRealtimeClientEventResponseCancel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventResponseCancel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventResponseCancel)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventResponseCancel(document.RootElement, options); } default: @@ -130,15 +105,20 @@ InternalRealtimeClientEventResponseCancel IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventResponseCancel FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventResponseCancel internalRealtimeClientEventResponseCancel) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventResponseCancel(document.RootElement); + if (internalRealtimeClientEventResponseCancel == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventResponseCancel, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventResponseCancel(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventResponseCancel(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCancel.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCancel.cs index f657c401f..4e7a1b227 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCancel.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCancel.cs @@ -9,12 +9,11 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventResponseCancel : InternalRealtimeClientEvent { - public InternalRealtimeClientEventResponseCancel() + public InternalRealtimeClientEventResponseCancel() : base(InternalRealtimeClientEventType.ResponseCancel) { - Kind = InternalRealtimeClientEventType.ResponseCancel; } - internal InternalRealtimeClientEventResponseCancel(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventResponseCancel(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties) : base(kind, eventId, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCreate.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCreate.Serialization.cs index 85a61db42..f1c98f3c9 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCreate.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCreate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventResponseCreate : IJsonModel { + internal InternalRealtimeClientEventResponseCreate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventResponseCreate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response") != true) { writer.WritePropertyName("response"u8); writer.WriteObjectValue(Response, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventResponseCreate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventResponseCreate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventResponseCreate)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventResponseCreate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventResponseCreate(document.RootElement, options); } - internal static InternalRealtimeClientEventResponseCreate DeserializeInternalRealtimeClientEventResponseCreate(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventResponseCreate DeserializeInternalRealtimeClientEventResponseCreate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeClientEventResponseCreateResponse response = default; - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeClientEventResponseCreateResponse response = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response"u8)) + if (prop.NameEquals("type"u8)) { - response = InternalRealtimeClientEventResponseCreateResponse.DeserializeInternalRealtimeClientEventResponseCreateResponse(property.Value, options); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("response"u8)) { - eventId = property.Value.GetString(); + response = InternalRealtimeClientEventResponseCreateResponse.DeserializeInternalRealtimeClientEventResponseCreateResponse(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventResponseCreate(type, eventId, serializedAdditionalRawData, response); + return new InternalRealtimeClientEventResponseCreate(kind, eventId, additionalBinaryDataProperties, response); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalRealtimeClientEventResponseCreate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventResponseCreate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventResponseCreate)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventResponseCreate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRealtimeClientEventResponseCreate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventResponseCreate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventResponseCreate internalRealtimeClientEventResponseCreate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventResponseCreate(document.RootElement); + if (internalRealtimeClientEventResponseCreate == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventResponseCreate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventResponseCreate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventResponseCreate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCreate.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCreate.cs index 93cdb4261..349d8e180 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCreate.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCreate.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventResponseCreate : InternalRealtimeClientEvent { - public InternalRealtimeClientEventResponseCreate(InternalRealtimeClientEventResponseCreateResponse response) + public InternalRealtimeClientEventResponseCreate(InternalRealtimeClientEventResponseCreateResponse response) : base(InternalRealtimeClientEventType.ResponseCreate) { Argument.AssertNotNull(response, nameof(response)); - Kind = InternalRealtimeClientEventType.ResponseCreate; Response = response; } - internal InternalRealtimeClientEventResponseCreate(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeClientEventResponseCreateResponse response) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventResponseCreate(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, InternalRealtimeClientEventResponseCreateResponse response) : base(kind, eventId, additionalBinaryDataProperties) { Response = response; } - internal InternalRealtimeClientEventResponseCreate() - { - } - public InternalRealtimeClientEventResponseCreateResponse Response { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.Serialization.cs index e44ae3928..e5feb25ba 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,80 +15,90 @@ internal partial class InternalRealtimeClientEventResponseCreateResponse : IJson { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventResponseCreateResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("modalities") != true && Optional.IsCollectionDefined(Modalities)) + if (Optional.IsCollectionDefined(Modalities) && _additionalBinaryDataProperties?.ContainsKey("modalities") != true) { writer.WritePropertyName("modalities"u8); writer.WriteStartArray(); - foreach (var item in Modalities) + foreach (string item in Modalities) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(Instructions)) + if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { writer.WritePropertyName("instructions"u8); writer.WriteStringValue(Instructions); } - if (SerializedAdditionalRawData?.ContainsKey("voice") != true && Optional.IsDefined(Voice)) + if (Optional.IsDefined(Voice) && _additionalBinaryDataProperties?.ContainsKey("voice") != true) { writer.WritePropertyName("voice"u8); writer.WriteStringValue(Voice); } - if (SerializedAdditionalRawData?.ContainsKey("output_audio_format") != true && Optional.IsDefined(OutputAudioFormat)) + if (Optional.IsDefined(OutputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("output_audio_format") != true) { writer.WritePropertyName("output_audio_format"u8); writer.WriteStringValue(OutputAudioFormat); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(Tools)) + if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ConversationTool item in Tools) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true && Optional.IsDefined(ToolChoice)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { - writer.WritePropertyName("tool_choice"u8); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(MaxOutputTokens) && _additionalBinaryDataProperties?.ContainsKey("max_output_tokens") != true) + { + writer.WritePropertyName("max_output_tokens"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(ToolChoice); + writer.WriteRawValue(MaxOutputTokens); #else - using (JsonDocument document = JsonDocument.Parse(ToolChoice)) + using (JsonDocument document = JsonDocument.Parse(MaxOutputTokens)) { JsonSerializer.Serialize(writer, document.RootElement); } #endif } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(ToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { - writer.WritePropertyName("temperature"u8); - writer.WriteNumberValue(Temperature.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("max_output_tokens") != true && Optional.IsDefined(MaxOutputTokens)) - { - writer.WritePropertyName("max_output_tokens"u8); + writer.WritePropertyName("tool_choice"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(MaxOutputTokens); + writer.WriteRawValue(ToolChoice); #else - using (JsonDocument document = JsonDocument.Parse(MaxOutputTokens)) + using (JsonDocument document = JsonDocument.Parse(ToolChoice)) { JsonSerializer.Serialize(writer, document.RootElement); } #endif } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -95,7 +106,7 @@ void IJsonModel.Write(Utf8Jso } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -104,25 +115,23 @@ void IJsonModel.Write(Utf8Jso #endif } } - writer.WriteEndObject(); } - InternalRealtimeClientEventResponseCreateResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventResponseCreateResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeClientEventResponseCreateResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventResponseCreateResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventResponseCreateResponse(document.RootElement, options); } - internal static InternalRealtimeClientEventResponseCreateResponse DeserializeInternalRealtimeClientEventResponseCreateResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventResponseCreateResponse DeserializeInternalRealtimeClientEventResponseCreateResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -132,106 +141,111 @@ internal static InternalRealtimeClientEventResponseCreateResponse DeserializeInt string voice = default; string outputAudioFormat = default; IList tools = default; - BinaryData toolChoice = default; float? temperature = default; BinaryData maxOutputTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData toolChoice = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("modalities"u8)) + if (prop.NameEquals("modalities"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } modalities = array; continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("voice"u8)) + if (prop.NameEquals("voice"u8)) { - voice = property.Value.GetString(); + voice = prop.Value.GetString(); continue; } - if (property.NameEquals("output_audio_format"u8)) + if (prop.NameEquals("output_audio_format"u8)) { - outputAudioFormat = property.Value.GetString(); + outputAudioFormat = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ConversationTool.DeserializeConversationTool(item, options)); } tools = array; continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - toolChoice = BinaryData.FromString(property.Value.GetRawText()); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("max_output_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - temperature = property.Value.GetSingle(); + maxOutputTokens = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("max_output_tokens"u8)) + if (prop.NameEquals("tool_choice"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - maxOutputTokens = BinaryData.FromString(property.Value.GetRawText()); + toolChoice = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeClientEventResponseCreateResponse( modalities ?? new ChangeTrackingList(), instructions, voice, outputAudioFormat, tools ?? new ChangeTrackingList(), - toolChoice, temperature, maxOutputTokens, - serializedAdditionalRawData); + toolChoice, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -241,15 +255,16 @@ BinaryData IPersistableModel. } } - InternalRealtimeClientEventResponseCreateResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventResponseCreateResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeClientEventResponseCreateResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventResponseCreateResponse(document.RootElement, options); } default: @@ -259,15 +274,20 @@ InternalRealtimeClientEventResponseCreateResponse IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeClientEventResponseCreateResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventResponseCreateResponse internalRealtimeClientEventResponseCreateResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventResponseCreateResponse(document.RootElement); + if (internalRealtimeClientEventResponseCreateResponse == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventResponseCreateResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventResponseCreateResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventResponseCreateResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.cs b/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.cs index 8f493bd76..652404768 100644 --- a/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.cs +++ b/src/Generated/Models/InternalRealtimeClientEventResponseCreateResponse.cs @@ -4,37 +4,51 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventResponseCreateResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalRealtimeClientEventResponseCreateResponse() { Modalities = new ChangeTrackingList(); Tools = new ChangeTrackingList(); } - internal InternalRealtimeClientEventResponseCreateResponse(IList modalities, string instructions, string voice, string outputAudioFormat, IList tools, BinaryData toolChoice, float? temperature, BinaryData maxOutputTokens, IDictionary serializedAdditionalRawData) + internal InternalRealtimeClientEventResponseCreateResponse(IList modalities, string instructions, string voice, string outputAudioFormat, IList tools, float? temperature, BinaryData maxOutputTokens, BinaryData toolChoice, IDictionary additionalBinaryDataProperties) { Modalities = modalities; Instructions = instructions; Voice = voice; OutputAudioFormat = outputAudioFormat; Tools = tools; - ToolChoice = toolChoice; Temperature = temperature; MaxOutputTokens = maxOutputTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; + ToolChoice = toolChoice; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList Modalities { get; } + public string Instructions { get; set; } + public string Voice { get; set; } + public string OutputAudioFormat { get; set; } + public IList Tools { get; } + public float? Temperature { get; set; } + public BinaryData MaxOutputTokens { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.Serialization.cs b/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.Serialization.cs index a5305a57a..18a9d1611 100644 --- a/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventSessionUpdate : IJsonModel { + internal InternalRealtimeClientEventSessionUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEventSessionUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("session") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("session") != true) { writer.WritePropertyName("session"u8); writer.WriteObjectValue(Session, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeClientEventSessionUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEventSessionUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeClientEventSessionUpdate)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEventSessionUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEventSessionUpdate(document.RootElement, options); } - internal static InternalRealtimeClientEventSessionUpdate DeserializeInternalRealtimeClientEventSessionUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeClientEventSessionUpdate DeserializeInternalRealtimeClientEventSessionUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationSessionOptions session = default; - InternalRealtimeClientEventType type = default; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + ConversationSessionOptions session = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("session"u8)) + if (prop.NameEquals("type"u8)) { - session = ConversationSessionOptions.DeserializeConversationSessionOptions(property.Value, options); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("session"u8)) { - eventId = property.Value.GetString(); + session = ConversationSessionOptions.DeserializeConversationSessionOptions(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeClientEventSessionUpdate(type, eventId, serializedAdditionalRawData, session); + return new InternalRealtimeClientEventSessionUpdate(kind, eventId, additionalBinaryDataProperties, session); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalRealtimeClientEventSessionUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEventSessionUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeClientEventSessionUpdate)PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEventSessionUpdate(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRealtimeClientEventSessionUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeClientEventSessionUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeClientEventSessionUpdate internalRealtimeClientEventSessionUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeClientEventSessionUpdate(document.RootElement); + if (internalRealtimeClientEventSessionUpdate == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeClientEventSessionUpdate, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeClientEventSessionUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeClientEventSessionUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.cs b/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.cs index 8951177f4..8787b40d4 100644 --- a/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.cs +++ b/src/Generated/Models/InternalRealtimeClientEventSessionUpdate.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeClientEventSessionUpdate : InternalRealtimeClientEvent { - public InternalRealtimeClientEventSessionUpdate(ConversationSessionOptions session) + public InternalRealtimeClientEventSessionUpdate(ConversationSessionOptions session) : base(InternalRealtimeClientEventType.SessionUpdate) { Argument.AssertNotNull(session, nameof(session)); - Kind = InternalRealtimeClientEventType.SessionUpdate; Session = session; } - internal InternalRealtimeClientEventSessionUpdate(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData, ConversationSessionOptions session) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeClientEventSessionUpdate(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties, ConversationSessionOptions session) : base(kind, eventId, additionalBinaryDataProperties) { Session = session; } - internal InternalRealtimeClientEventSessionUpdate() - { - } - public ConversationSessionOptions Session { get; } } } diff --git a/src/Generated/Models/InternalRealtimeClientEventType.cs b/src/Generated/Models/InternalRealtimeClientEventType.cs index dc56ef0ee..c59b899e9 100644 --- a/src/Generated/Models/InternalRealtimeClientEventType.cs +++ b/src/Generated/Models/InternalRealtimeClientEventType.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeClientEventType : IEquatable { private readonly string _value; - - public InternalRealtimeClientEventType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string SessionUpdateValue = "session.update"; private const string InputAudioBufferAppendValue = "input_audio_buffer.append"; private const string InputAudioBufferCommitValue = "input_audio_buffer.commit"; @@ -26,25 +21,45 @@ public InternalRealtimeClientEventType(string value) private const string ResponseCreateValue = "response.create"; private const string ResponseCancelValue = "response.cancel"; + public InternalRealtimeClientEventType(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalRealtimeClientEventType SessionUpdate { get; } = new InternalRealtimeClientEventType(SessionUpdateValue); + public static InternalRealtimeClientEventType InputAudioBufferAppend { get; } = new InternalRealtimeClientEventType(InputAudioBufferAppendValue); + public static InternalRealtimeClientEventType InputAudioBufferCommit { get; } = new InternalRealtimeClientEventType(InputAudioBufferCommitValue); + public static InternalRealtimeClientEventType InputAudioBufferClear { get; } = new InternalRealtimeClientEventType(InputAudioBufferClearValue); + public static InternalRealtimeClientEventType ConversationItemCreate { get; } = new InternalRealtimeClientEventType(ConversationItemCreateValue); + public static InternalRealtimeClientEventType ConversationItemDelete { get; } = new InternalRealtimeClientEventType(ConversationItemDeleteValue); + public static InternalRealtimeClientEventType ConversationItemTruncate { get; } = new InternalRealtimeClientEventType(ConversationItemTruncateValue); + public static InternalRealtimeClientEventType ResponseCreate { get; } = new InternalRealtimeClientEventType(ResponseCreateValue); + public static InternalRealtimeClientEventType ResponseCancel { get; } = new InternalRealtimeClientEventType(ResponseCancelValue); + public static bool operator ==(InternalRealtimeClientEventType left, InternalRealtimeClientEventType right) => left.Equals(right); + public static bool operator !=(InternalRealtimeClientEventType left, InternalRealtimeClientEventType right) => !left.Equals(right); + public static implicit operator InternalRealtimeClientEventType(string value) => new InternalRealtimeClientEventType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeClientEventType other && Equals(other); + public bool Equals(InternalRealtimeClientEventType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeItemType.cs b/src/Generated/Models/InternalRealtimeItemType.cs index a817e210b..23bc8f6eb 100644 --- a/src/Generated/Models/InternalRealtimeItemType.cs +++ b/src/Generated/Models/InternalRealtimeItemType.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeItemType : IEquatable { private readonly string _value; + private const string MessageValue = "message"; + private const string FunctionCallValue = "function_call"; + private const string FunctionCallOutputValue = "function_call_output"; public InternalRealtimeItemType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string MessageValue = "message"; - private const string FunctionCallValue = "function_call"; - private const string FunctionCallOutputValue = "function_call_output"; + _value = value; + } public static InternalRealtimeItemType Message { get; } = new InternalRealtimeItemType(MessageValue); + public static InternalRealtimeItemType FunctionCall { get; } = new InternalRealtimeItemType(FunctionCallValue); + public static InternalRealtimeItemType FunctionCallOutput { get; } = new InternalRealtimeItemType(FunctionCallOutputValue); + public static bool operator ==(InternalRealtimeItemType left, InternalRealtimeItemType right) => left.Equals(right); + public static bool operator !=(InternalRealtimeItemType left, InternalRealtimeItemType right) => !left.Equals(right); + public static implicit operator InternalRealtimeItemType(string value) => new InternalRealtimeItemType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeItemType other && Equals(other); + public bool Equals(InternalRealtimeItemType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.Serialization.cs index 278b83108..2b01e29e1 100644 --- a/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.Serialization.cs @@ -7,155 +7,123 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestAssistantMessageItem : IJsonModel { + internal InternalRealtimeRequestAssistantMessageItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestAssistantMessageItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ConversationContentPart item in Content) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("status") != true && Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestAssistantMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestAssistantMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestAssistantMessageItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestAssistantMessageItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestAssistantMessageItem(document.RootElement, options); } - internal static InternalRealtimeRequestAssistantMessageItem DeserializeInternalRealtimeRequestAssistantMessageItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestAssistantMessageItem DeserializeInternalRealtimeRequestAssistantMessageItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList content = default; + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); ConversationMessageRole role = default; ConversationItemStatus? status = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList content = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("type"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); - } - content = array; + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("id"u8)) { - role = new ConversationMessageRole(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ConversationItemStatus(property.Value.GetString()); + role = new ConversationMessageRole(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("status"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new ConversationItemStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("content"u8)) { - id = property.Value.GetString(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); + } + content = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeRequestAssistantMessageItem( - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, role, status, content); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -165,15 +133,16 @@ BinaryData IPersistableModel.Write( } } - InternalRealtimeRequestAssistantMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestAssistantMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestAssistantMessageItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestAssistantMessageItem(document.RootElement, options); } default: @@ -183,15 +152,20 @@ InternalRealtimeRequestAssistantMessageItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestAssistantMessageItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestAssistantMessageItem internalRealtimeRequestAssistantMessageItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestAssistantMessageItem(document.RootElement); + if (internalRealtimeRequestAssistantMessageItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestAssistantMessageItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestAssistantMessageItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestAssistantMessageItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.cs b/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.cs index d016eca30..a3fa292b3 100644 --- a/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestAssistantMessageItem.cs @@ -4,19 +4,14 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestAssistantMessageItem : InternalRealtimeRequestMessageItem { - internal InternalRealtimeRequestAssistantMessageItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(type, id, serializedAdditionalRawData, role, status) + internal InternalRealtimeRequestAssistantMessageItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(@type, id, additionalBinaryDataProperties, role, status) { Content = content; } - - internal InternalRealtimeRequestAssistantMessageItem() - { - } } } diff --git a/src/Generated/Models/InternalRealtimeRequestAudioContentPart.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestAudioContentPart.Serialization.cs index 6ade9d52d..1ca220773 100644 --- a/src/Generated/Models/InternalRealtimeRequestAudioContentPart.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestAudioContentPart.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,106 +15,84 @@ internal partial class InternalRealtimeRequestAudioContentPart : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestAudioContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("transcript") != true && Optional.IsDefined(InternalTranscriptValue)) + if (Optional.IsDefined(InternalTranscriptValue) && _additionalBinaryDataProperties?.ContainsKey("transcript") != true) { writer.WritePropertyName("transcript"u8); writer.WriteStringValue(InternalTranscriptValue); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestAudioContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestAudioContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestAudioContentPart)JsonModelCreateCore(ref reader, options); + + protected override ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestAudioContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestAudioContentPart(document.RootElement, options); } - internal static InternalRealtimeRequestAudioContentPart DeserializeInternalRealtimeRequestAudioContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestAudioContentPart DeserializeInternalRealtimeRequestAudioContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - string transcript = default; - ConversationContentPartKind type0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPartKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = "input_audio"; + string internalTranscriptValue = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + kind = new ConversationContentPartKind(prop.Value.GetString()); continue; } - if (property.NameEquals("transcript"u8)) + if (prop.NameEquals("type"u8)) { - transcript = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("transcript"u8)) { - type0 = new ConversationContentPartKind(property.Value.GetString()); + internalTranscriptValue = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeRequestAudioContentPart(type0, serializedAdditionalRawData, type, transcript); + return new InternalRealtimeRequestAudioContentPart(kind, additionalBinaryDataProperties, @type, internalTranscriptValue); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +102,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalRealtimeRequestAudioContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestAudioContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestAudioContentPart)PersistableModelCreateCore(data, options); + protected override ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestAudioContentPart(document.RootElement, options); } default: @@ -141,15 +121,20 @@ InternalRealtimeRequestAudioContentPart IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestAudioContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestAudioContentPart internalRealtimeRequestAudioContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestAudioContentPart(document.RootElement); + if (internalRealtimeRequestAudioContentPart == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestAudioContentPart, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestAudioContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestAudioContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestAudioContentPart.cs b/src/Generated/Models/InternalRealtimeRequestAudioContentPart.cs index 4c8361826..b2d6153b0 100644 --- a/src/Generated/Models/InternalRealtimeRequestAudioContentPart.cs +++ b/src/Generated/Models/InternalRealtimeRequestAudioContentPart.cs @@ -9,14 +9,13 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestAudioContentPart : ConversationContentPart { - public InternalRealtimeRequestAudioContentPart() + public InternalRealtimeRequestAudioContentPart() : base(ConversationContentPartKind.InputAudio) { - Kind = ConversationContentPartKind.InputAudio; } - internal InternalRealtimeRequestAudioContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData, string type, string internalTranscriptValue) : base(kind, serializedAdditionalRawData) + internal InternalRealtimeRequestAudioContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties, string @type, string internalTranscriptValue) : base(kind, additionalBinaryDataProperties) { - Type = type; + Type = @type; InternalTranscriptValue = internalTranscriptValue; } diff --git a/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.Serialization.cs index 6b686671b..37fec87f7 100644 --- a/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.Serialization.cs @@ -7,157 +7,135 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestFunctionCallItem : IJsonModel { + internal InternalRealtimeRequestFunctionCallItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestFunctionCallItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true && Optional.IsDefined(Status)) + if (Optional.IsDefined(Status) && _additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestFunctionCallItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestFunctionCallItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestFunctionCallItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestFunctionCallItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestFunctionCallItem(document.RootElement, options); } - internal static InternalRealtimeRequestFunctionCallItem DeserializeInternalRealtimeRequestFunctionCallItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestFunctionCallItem DeserializeInternalRealtimeRequestFunctionCallItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string name = default; string callId = default; string arguments = default; ConversationItemStatus? status = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("type"u8)) { - name = property.Value.GetString(); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("id"u8)) { - callId = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("name"u8)) { - arguments = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("call_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ConversationItemStatus(property.Value.GetString()); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("arguments"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + arguments = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("status"u8)) { - id = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new ConversationItemStatus(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeRequestFunctionCallItem( - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, name, callId, arguments, status); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -167,15 +145,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalRealtimeRequestFunctionCallItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestFunctionCallItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestFunctionCallItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestFunctionCallItem(document.RootElement, options); } default: @@ -185,15 +164,20 @@ InternalRealtimeRequestFunctionCallItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestFunctionCallItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestFunctionCallItem internalRealtimeRequestFunctionCallItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestFunctionCallItem(document.RootElement); + if (internalRealtimeRequestFunctionCallItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestFunctionCallItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestFunctionCallItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestFunctionCallItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.cs b/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.cs index ff1836f44..da0da8dbe 100644 --- a/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestFunctionCallItem.cs @@ -4,24 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestFunctionCallItem : ConversationItem { - public InternalRealtimeRequestFunctionCallItem(string name, string callId, string arguments) + public InternalRealtimeRequestFunctionCallItem(string name, string callId, string arguments) : base(InternalRealtimeItemType.FunctionCall) { Argument.AssertNotNull(name, nameof(name)); Argument.AssertNotNull(callId, nameof(callId)); Argument.AssertNotNull(arguments, nameof(arguments)); - Type = InternalRealtimeItemType.FunctionCall; Name = name; CallId = callId; Arguments = arguments; } - internal InternalRealtimeRequestFunctionCallItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, string name, string callId, string arguments, ConversationItemStatus? status) : base(type, id, serializedAdditionalRawData) + internal InternalRealtimeRequestFunctionCallItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, string name, string callId, string arguments, ConversationItemStatus? status) : base(@type, id, additionalBinaryDataProperties) { Name = name; CallId = callId; @@ -29,13 +29,12 @@ internal InternalRealtimeRequestFunctionCallItem(InternalRealtimeItemType type, Status = status; } - internal InternalRealtimeRequestFunctionCallItem() - { - } - public string Name { get; } + public string CallId { get; } + public string Arguments { get; } + public ConversationItemStatus? Status { get; set; } } } diff --git a/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.Serialization.cs index bc921ff6f..f27e4810a 100644 --- a/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.Serialization.cs @@ -7,124 +7,102 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestFunctionCallOutputItem : IJsonModel { + internal InternalRealtimeRequestFunctionCallOutputItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestFunctionCallOutputItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("output") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output") != true) { writer.WritePropertyName("output"u8); writer.WriteStringValue(Output); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestFunctionCallOutputItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestFunctionCallOutputItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestFunctionCallOutputItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestFunctionCallOutputItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestFunctionCallOutputItem(document.RootElement, options); } - internal static InternalRealtimeRequestFunctionCallOutputItem DeserializeInternalRealtimeRequestFunctionCallOutputItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestFunctionCallOutputItem DeserializeInternalRealtimeRequestFunctionCallOutputItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string callId = default; string output = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("type"u8)) { - callId = property.Value.GetString(); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("id"u8)) { - output = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("call_id"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("output"u8)) { - id = property.Value.GetString(); + output = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeRequestFunctionCallOutputItem(type, id, serializedAdditionalRawData, callId, output); + return new InternalRealtimeRequestFunctionCallOutputItem(@type, id, additionalBinaryDataProperties, callId, output); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +112,16 @@ BinaryData IPersistableModel.Writ } } - InternalRealtimeRequestFunctionCallOutputItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestFunctionCallOutputItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestFunctionCallOutputItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestFunctionCallOutputItem(document.RootElement, options); } default: @@ -152,15 +131,20 @@ InternalRealtimeRequestFunctionCallOutputItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestFunctionCallOutputItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestFunctionCallOutputItem internalRealtimeRequestFunctionCallOutputItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestFunctionCallOutputItem(document.RootElement); + if (internalRealtimeRequestFunctionCallOutputItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestFunctionCallOutputItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestFunctionCallOutputItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestFunctionCallOutputItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.cs b/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.cs index 443ec884c..1a65bed0c 100644 --- a/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestFunctionCallOutputItem.cs @@ -4,32 +4,29 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestFunctionCallOutputItem : ConversationItem { - public InternalRealtimeRequestFunctionCallOutputItem(string callId, string output) + public InternalRealtimeRequestFunctionCallOutputItem(string callId, string output) : base(InternalRealtimeItemType.FunctionCallOutput) { Argument.AssertNotNull(callId, nameof(callId)); Argument.AssertNotNull(output, nameof(output)); - Type = InternalRealtimeItemType.FunctionCallOutput; CallId = callId; Output = output; } - internal InternalRealtimeRequestFunctionCallOutputItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, string callId, string output) : base(type, id, serializedAdditionalRawData) + internal InternalRealtimeRequestFunctionCallOutputItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, string callId, string output) : base(@type, id, additionalBinaryDataProperties) { CallId = callId; Output = output; } - internal InternalRealtimeRequestFunctionCallOutputItem() - { - } - public string CallId { get; } + public string Output { get; } } } diff --git a/src/Generated/Models/InternalRealtimeRequestMessageItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestMessageItem.Serialization.cs index 893d108dd..33ef849ee 100644 --- a/src/Generated/Models/InternalRealtimeRequestMessageItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestMessageItem.Serialization.cs @@ -5,139 +5,83 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestMessageItem : IJsonModel { + internal InternalRealtimeRequestMessageItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestMessageItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("role") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) { writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true && Optional.IsDefined(Status)) + if (Optional.IsDefined(Status) && _additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestMessageItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestMessageItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestMessageItem(document.RootElement, options); } - internal static InternalRealtimeRequestMessageItem DeserializeInternalRealtimeRequestMessageItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestMessageItem DeserializeInternalRealtimeRequestMessageItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("role", out JsonElement discriminator)) + if (element.TryGetProperty("role"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "assistant": return InternalRealtimeRequestAssistantMessageItem.DeserializeInternalRealtimeRequestAssistantMessageItem(element, options); - case "system": return InternalRealtimeRequestSystemMessageItem.DeserializeInternalRealtimeRequestSystemMessageItem(element, options); - case "user": return InternalRealtimeRequestUserMessageItem.DeserializeInternalRealtimeRequestUserMessageItem(element, options); + case "system": + return InternalRealtimeRequestSystemMessageItem.DeserializeInternalRealtimeRequestSystemMessageItem(element, options); + case "user": + return InternalRealtimeRequestUserMessageItem.DeserializeInternalRealtimeRequestUserMessageItem(element, options); + case "assistant": + return InternalRealtimeRequestAssistantMessageItem.DeserializeInternalRealtimeRequestAssistantMessageItem(element, options); } } - ConversationMessageRole role = "message"; - ConversationItemStatus? status = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("role"u8)) - { - role = new ConversationMessageRole(property.Value.GetString()); - continue; - } - if (property.NameEquals("status"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ConversationItemStatus(property.Value.GetString()); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new InternalRealtimeItemType(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeRequestMessageItem(type, id, serializedAdditionalRawData, role, status); + return UnknownRealtimeRequestMessageItem.DeserializeUnknownRealtimeRequestMessageItem(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -147,15 +91,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - InternalRealtimeRequestMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestMessageItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestMessageItem(document.RootElement, options); } default: @@ -165,15 +110,20 @@ InternalRealtimeRequestMessageItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestMessageItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestMessageItem internalRealtimeRequestMessageItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestMessageItem(document.RootElement); + if (internalRealtimeRequestMessageItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestMessageItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestMessageItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestMessageItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestMessageItem.cs b/src/Generated/Models/InternalRealtimeRequestMessageItem.cs index 7cbb6351b..c1b1befef 100644 --- a/src/Generated/Models/InternalRealtimeRequestMessageItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestMessageItem.cs @@ -9,18 +9,19 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestMessageItem : ConversationItem { - public InternalRealtimeRequestMessageItem() + public InternalRealtimeRequestMessageItem(ConversationMessageRole role) : base(InternalRealtimeItemType.Message) { - Role = new ConversationMessageRole("message"); + Role = role; } - internal InternalRealtimeRequestMessageItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, ConversationMessageRole role, ConversationItemStatus? status) : base(type, id, serializedAdditionalRawData) + internal InternalRealtimeRequestMessageItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, ConversationMessageRole role, ConversationItemStatus? status) : base(@type, id, additionalBinaryDataProperties) { Role = role; Status = status; } internal ConversationMessageRole Role { get; set; } + public ConversationItemStatus? Status { get; set; } } } diff --git a/src/Generated/Models/InternalRealtimeRequestSessionModality.cs b/src/Generated/Models/InternalRealtimeRequestSessionModality.cs index c57d27eb2..2fd764039 100644 --- a/src/Generated/Models/InternalRealtimeRequestSessionModality.cs +++ b/src/Generated/Models/InternalRealtimeRequestSessionModality.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeRequestSessionModality : IEquatable { private readonly string _value; + private const string TextValue = "text"; + private const string AudioValue = "audio"; public InternalRealtimeRequestSessionModality(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string TextValue = "text"; - private const string AudioValue = "audio"; + _value = value; + } public static InternalRealtimeRequestSessionModality Text { get; } = new InternalRealtimeRequestSessionModality(TextValue); + public static InternalRealtimeRequestSessionModality Audio { get; } = new InternalRealtimeRequestSessionModality(AudioValue); + public static bool operator ==(InternalRealtimeRequestSessionModality left, InternalRealtimeRequestSessionModality right) => left.Equals(right); + public static bool operator !=(InternalRealtimeRequestSessionModality left, InternalRealtimeRequestSessionModality right) => !left.Equals(right); + public static implicit operator InternalRealtimeRequestSessionModality(string value) => new InternalRealtimeRequestSessionModality(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeRequestSessionModality other && Equals(other); + public bool Equals(InternalRealtimeRequestSessionModality other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.Serialization.cs index 4bc4c361b..e6863613e 100644 --- a/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.Serialization.cs @@ -7,155 +7,123 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestSystemMessageItem : IJsonModel { + internal InternalRealtimeRequestSystemMessageItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestSystemMessageItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ConversationContentPart item in Content) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("status") != true && Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestSystemMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestSystemMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestSystemMessageItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestSystemMessageItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestSystemMessageItem(document.RootElement, options); } - internal static InternalRealtimeRequestSystemMessageItem DeserializeInternalRealtimeRequestSystemMessageItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestSystemMessageItem DeserializeInternalRealtimeRequestSystemMessageItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList content = default; + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); ConversationMessageRole role = default; ConversationItemStatus? status = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList content = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("type"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); - } - content = array; + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("id"u8)) { - role = new ConversationMessageRole(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ConversationItemStatus(property.Value.GetString()); + role = new ConversationMessageRole(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("status"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new ConversationItemStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("content"u8)) { - id = property.Value.GetString(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); + } + content = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeRequestSystemMessageItem( - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, role, status, content); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -165,15 +133,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalRealtimeRequestSystemMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestSystemMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestSystemMessageItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestSystemMessageItem(document.RootElement, options); } default: @@ -183,15 +152,20 @@ InternalRealtimeRequestSystemMessageItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestSystemMessageItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestSystemMessageItem internalRealtimeRequestSystemMessageItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestSystemMessageItem(document.RootElement); + if (internalRealtimeRequestSystemMessageItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestSystemMessageItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestSystemMessageItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestSystemMessageItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.cs b/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.cs index a949e1ca4..ac11a9ce9 100644 --- a/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestSystemMessageItem.cs @@ -4,19 +4,14 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestSystemMessageItem : InternalRealtimeRequestMessageItem { - internal InternalRealtimeRequestSystemMessageItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(type, id, serializedAdditionalRawData, role, status) + internal InternalRealtimeRequestSystemMessageItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(@type, id, additionalBinaryDataProperties, role, status) { Content = content; } - - internal InternalRealtimeRequestSystemMessageItem() - { - } } } diff --git a/src/Generated/Models/InternalRealtimeRequestTextContentPart.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestTextContentPart.Serialization.cs index 75c01f2f8..2a1e7d277 100644 --- a/src/Generated/Models/InternalRealtimeRequestTextContentPart.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestTextContentPart.Serialization.cs @@ -7,113 +7,96 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestTextContentPart : IJsonModel { + internal InternalRealtimeRequestTextContentPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestTextContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(InternalTextValue); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestTextContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestTextContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestTextContentPart)JsonModelCreateCore(ref reader, options); + + protected override ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestTextContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestTextContentPart(document.RootElement, options); } - internal static InternalRealtimeRequestTextContentPart DeserializeInternalRealtimeRequestTextContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestTextContentPart DeserializeInternalRealtimeRequestTextContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - string text = default; - ConversationContentPartKind type0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPartKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = "input_text"; + string internalTextValue = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + kind = new ConversationContentPartKind(prop.Value.GetString()); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("type"u8)) { - text = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("text"u8)) { - type0 = new ConversationContentPartKind(property.Value.GetString()); + internalTextValue = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeRequestTextContentPart(type0, serializedAdditionalRawData, type, text); + return new InternalRealtimeRequestTextContentPart(kind, additionalBinaryDataProperties, @type, internalTextValue); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +106,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalRealtimeRequestTextContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestTextContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestTextContentPart)PersistableModelCreateCore(data, options); + protected override ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestTextContentPart(document.RootElement, options); } default: @@ -141,15 +125,20 @@ InternalRealtimeRequestTextContentPart IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestTextContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestTextContentPart internalRealtimeRequestTextContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestTextContentPart(document.RootElement); + if (internalRealtimeRequestTextContentPart == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestTextContentPart, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestTextContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestTextContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestTextContentPart.cs b/src/Generated/Models/InternalRealtimeRequestTextContentPart.cs index c74d9851b..072b1dc59 100644 --- a/src/Generated/Models/InternalRealtimeRequestTextContentPart.cs +++ b/src/Generated/Models/InternalRealtimeRequestTextContentPart.cs @@ -4,29 +4,25 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestTextContentPart : ConversationContentPart { - public InternalRealtimeRequestTextContentPart(string internalTextValue) + public InternalRealtimeRequestTextContentPart(string internalTextValue) : base(ConversationContentPartKind.InputText) { Argument.AssertNotNull(internalTextValue, nameof(internalTextValue)); - Kind = ConversationContentPartKind.InputText; InternalTextValue = internalTextValue; } - internal InternalRealtimeRequestTextContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData, string type, string internalTextValue) : base(kind, serializedAdditionalRawData) + internal InternalRealtimeRequestTextContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties, string @type, string internalTextValue) : base(kind, additionalBinaryDataProperties) { - Type = type; + Type = @type; InternalTextValue = internalTextValue; } - internal InternalRealtimeRequestTextContentPart() - { - } - internal string Type { get; set; } = "input_text"; } } diff --git a/src/Generated/Models/InternalRealtimeRequestUserMessageItem.Serialization.cs b/src/Generated/Models/InternalRealtimeRequestUserMessageItem.Serialization.cs index b2be957c1..3728f9a62 100644 --- a/src/Generated/Models/InternalRealtimeRequestUserMessageItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeRequestUserMessageItem.Serialization.cs @@ -7,155 +7,123 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestUserMessageItem : IJsonModel { + internal InternalRealtimeRequestUserMessageItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestUserMessageItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ConversationContentPart item in Content) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("status") != true && Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeRequestUserMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeRequestUserMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeRequestUserMessageItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeRequestUserMessageItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeRequestUserMessageItem(document.RootElement, options); } - internal static InternalRealtimeRequestUserMessageItem DeserializeInternalRealtimeRequestUserMessageItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeRequestUserMessageItem DeserializeInternalRealtimeRequestUserMessageItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList content = default; + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); ConversationMessageRole role = default; ConversationItemStatus? status = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList content = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("content"u8)) + if (prop.NameEquals("type"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); - } - content = array; + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("id"u8)) { - role = new ConversationMessageRole(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ConversationItemStatus(property.Value.GetString()); + role = new ConversationMessageRole(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("status"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new ConversationItemStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("content"u8)) { - id = property.Value.GetString(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); + } + content = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeRequestUserMessageItem( - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, role, status, content); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -165,15 +133,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalRealtimeRequestUserMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeRequestUserMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeRequestUserMessageItem)PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeRequestUserMessageItem(document.RootElement, options); } default: @@ -183,15 +152,20 @@ InternalRealtimeRequestUserMessageItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeRequestUserMessageItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeRequestUserMessageItem internalRealtimeRequestUserMessageItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeRequestUserMessageItem(document.RootElement); + if (internalRealtimeRequestUserMessageItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeRequestUserMessageItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeRequestUserMessageItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeRequestUserMessageItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeRequestUserMessageItem.cs b/src/Generated/Models/InternalRealtimeRequestUserMessageItem.cs index df7bebd09..8ef4a6272 100644 --- a/src/Generated/Models/InternalRealtimeRequestUserMessageItem.cs +++ b/src/Generated/Models/InternalRealtimeRequestUserMessageItem.cs @@ -4,19 +4,14 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeRequestUserMessageItem : InternalRealtimeRequestMessageItem { - internal InternalRealtimeRequestUserMessageItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(type, id, serializedAdditionalRawData, role, status) + internal InternalRealtimeRequestUserMessageItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, ConversationMessageRole role, ConversationItemStatus? status, IList content) : base(@type, id, additionalBinaryDataProperties, role, status) { Content = content; } - - internal InternalRealtimeRequestUserMessageItem() - { - } } } diff --git a/src/Generated/Models/InternalRealtimeResponse.Serialization.cs b/src/Generated/Models/InternalRealtimeResponse.Serialization.cs index 55de8801c..51ad43ae0 100644 --- a/src/Generated/Models/InternalRealtimeResponse.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponse.Serialization.cs @@ -7,36 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponse : IJsonModel { + internal InternalRealtimeResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("status_details") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status_details") != true) { if (StatusDetails != null) { @@ -45,27 +55,27 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } else { - writer.WriteNull("status_details"); + writer.WriteNull("statusDetails"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("output") != true) + if (_additionalBinaryDataProperties?.ContainsKey("usage") != true) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + if (_additionalBinaryDataProperties?.ContainsKey("output") != true) { writer.WritePropertyName("output"u8); writer.WriteStartArray(); - foreach (var item in Output) + foreach (ConversationItem item in Output) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true) - { - writer.WritePropertyName("usage"u8); - writer.WriteObjectValue(Usage, options); - } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -73,7 +83,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -82,25 +92,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead #endif } } - writer.WriteEndObject(); } - InternalRealtimeResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponse(document.RootElement, options); } - internal static InternalRealtimeResponse DeserializeInternalRealtimeResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponse DeserializeInternalRealtimeResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -109,73 +117,71 @@ internal static InternalRealtimeResponse DeserializeInternalRealtimeResponse(Jso string id = default; ConversationStatus status = default; ConversationStatusDetails statusDetails = default; - IReadOnlyList output = default; ConversationTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IReadOnlyList output = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalRealtimeResponseObject(property.Value.GetString()); + @object = new InternalRealtimeResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new ConversationStatus(property.Value.GetString()); + status = new ConversationStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("status_details"u8)) + if (prop.NameEquals("status_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { statusDetails = null; continue; } - statusDetails = ConversationStatusDetails.DeserializeConversationStatusDetails(property.Value, options); + statusDetails = ConversationStatusDetails.DeserializeConversationStatusDetails(prop.Value, options); + continue; + } + if (prop.NameEquals("usage"u8)) + { + usage = ConversationTokenUsage.DeserializeConversationTokenUsage(prop.Value, options); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("output"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ConversationItem.DeserializeConversationItem(item, options)); } output = array; continue; } - if (property.NameEquals("usage"u8)) - { - usage = ConversationTokenUsage.DeserializeConversationTokenUsage(property.Value, options); - continue; - } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeResponse( @object, id, status, statusDetails, - output, usage, - serializedAdditionalRawData); + output, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -185,15 +191,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOp } } - InternalRealtimeResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponse(document.RootElement, options); } default: @@ -203,15 +210,20 @@ InternalRealtimeResponse IPersistableModel.Create(Bina string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponse internalRealtimeResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponse(document.RootElement); + if (internalRealtimeResponse == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponse.cs b/src/Generated/Models/InternalRealtimeResponse.cs index 1c25584cd..50f4a0b40 100644 --- a/src/Generated/Models/InternalRealtimeResponse.cs +++ b/src/Generated/Models/InternalRealtimeResponse.cs @@ -10,40 +10,42 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalRealtimeResponse(string id, ConversationStatus status, ConversationStatusDetails statusDetails, IEnumerable output, ConversationTokenUsage usage) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(output, nameof(output)); - Argument.AssertNotNull(usage, nameof(usage)); + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRealtimeResponse(string id, ConversationStatus status, ConversationStatusDetails statusDetails, ConversationTokenUsage usage, IEnumerable output) + { Id = id; Status = status; StatusDetails = statusDetails; - Output = output.ToList(); Usage = usage; + Output = output.ToList(); } - internal InternalRealtimeResponse(InternalRealtimeResponseObject @object, string id, ConversationStatus status, ConversationStatusDetails statusDetails, IReadOnlyList output, ConversationTokenUsage usage, IDictionary serializedAdditionalRawData) + internal InternalRealtimeResponse(InternalRealtimeResponseObject @object, string id, ConversationStatus status, ConversationStatusDetails statusDetails, ConversationTokenUsage usage, IReadOnlyList output, IDictionary additionalBinaryDataProperties) { Object = @object; Id = id; Status = status; StatusDetails = statusDetails; - Output = output; Usage = usage; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRealtimeResponse() - { + Output = output; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalRealtimeResponseObject Object { get; } = InternalRealtimeResponseObject.RealtimeResponse; + public InternalRealtimeResponseObject Object { get; } = "realtime.response"; public string Id { get; } + public ConversationStatus Status { get; } + public ConversationStatusDetails StatusDetails { get; } + public ConversationTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeResponseAudioContentPart.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseAudioContentPart.Serialization.cs index 8c89c32ec..5a598301e 100644 --- a/src/Generated/Models/InternalRealtimeResponseAudioContentPart.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseAudioContentPart.Serialization.cs @@ -7,26 +7,37 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseAudioContentPart : IJsonModel { + internal InternalRealtimeResponseAudioContentPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseAudioContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("transcript") != true) + if (_additionalBinaryDataProperties?.ContainsKey("transcript") != true) { if (InternalTranscriptValue != null) { @@ -35,97 +46,69 @@ void IJsonModel.Write(Utf8JsonWriter w } else { - writer.WriteNull("transcript"); + writer.WriteNull("transcript"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeResponseAudioContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseAudioContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeResponseAudioContentPart)JsonModelCreateCore(ref reader, options); + + protected override ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseAudioContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseAudioContentPart(document.RootElement, options); } - internal static InternalRealtimeResponseAudioContentPart DeserializeInternalRealtimeResponseAudioContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseAudioContentPart DeserializeInternalRealtimeResponseAudioContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - string transcript = default; - ConversationContentPartKind type0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPartKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = "audio"; + string internalTranscriptValue = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + kind = new ConversationContentPartKind(prop.Value.GetString()); continue; } - if (property.NameEquals("transcript"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - transcript = null; - continue; - } - transcript = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("transcript"u8)) { - type0 = new ConversationContentPartKind(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + internalTranscriptValue = null; + continue; + } + internalTranscriptValue = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeResponseAudioContentPart(type0, serializedAdditionalRawData, type, transcript); + return new InternalRealtimeResponseAudioContentPart(kind, additionalBinaryDataProperties, @type, internalTranscriptValue); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +118,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalRealtimeResponseAudioContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseAudioContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeResponseAudioContentPart)PersistableModelCreateCore(data, options); + protected override ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseAudioContentPart(document.RootElement, options); } default: @@ -153,15 +137,20 @@ InternalRealtimeResponseAudioContentPart IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeResponseAudioContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseAudioContentPart internalRealtimeResponseAudioContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseAudioContentPart(document.RootElement); + if (internalRealtimeResponseAudioContentPart == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseAudioContentPart, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseAudioContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseAudioContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseAudioContentPart.cs b/src/Generated/Models/InternalRealtimeResponseAudioContentPart.cs index 257ce118f..f533cc688 100644 --- a/src/Generated/Models/InternalRealtimeResponseAudioContentPart.cs +++ b/src/Generated/Models/InternalRealtimeResponseAudioContentPart.cs @@ -9,22 +9,17 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseAudioContentPart : ConversationContentPart { - internal InternalRealtimeResponseAudioContentPart(string internalTranscriptValue) + internal InternalRealtimeResponseAudioContentPart(string internalTranscriptValue) : base(ConversationContentPartKind.OutputAudio) { - Kind = ConversationContentPartKind.OutputAudio; InternalTranscriptValue = internalTranscriptValue; } - internal InternalRealtimeResponseAudioContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData, string type, string internalTranscriptValue) : base(kind, serializedAdditionalRawData) + internal InternalRealtimeResponseAudioContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties, string @type, string internalTranscriptValue) : base(kind, additionalBinaryDataProperties) { - Type = type; + Type = @type; InternalTranscriptValue = internalTranscriptValue; } - internal InternalRealtimeResponseAudioContentPart() - { - } - internal string Type { get; set; } = "audio"; } } diff --git a/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.Serialization.cs index 3c24bb27a..14c3d3388 100644 --- a/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.Serialization.cs @@ -7,177 +7,143 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseFunctionCallItem : IJsonModel { + internal InternalRealtimeResponseFunctionCallItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseFunctionCallItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - if (Id != null) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - else - { - writer.WriteNull("id"); - } - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeResponseFunctionCallItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseFunctionCallItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeResponseFunctionCallItem)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeResponseItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseFunctionCallItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseFunctionCallItem(document.RootElement, options); } - internal static InternalRealtimeResponseFunctionCallItem DeserializeInternalRealtimeResponseFunctionCallItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseFunctionCallItem DeserializeInternalRealtimeResponseFunctionCallItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + InternalRealtimeResponseItemObject @object = default; + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string name = default; string callId = default; string arguments = default; ConversationItemStatus status = default; - InternalRealtimeResponseItemObject @object = default; - InternalRealtimeItemType type = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("object"u8)) { - name = property.Value.GetString(); + @object = new InternalRealtimeResponseItemObject(prop.Value.GetString()); continue; } - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("type"u8)) { - callId = property.Value.GetString(); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("id"u8)) { - arguments = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + id = null; + continue; + } + id = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("name"u8)) { - status = new ConversationItemStatus(property.Value.GetString()); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("call_id"u8)) { - @object = new InternalRealtimeResponseItemObject(property.Value.GetString()); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("arguments"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + arguments = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("status"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - id = null; - continue; - } - id = property.Value.GetString(); + status = new ConversationItemStatus(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeResponseFunctionCallItem( @object, - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, name, callId, arguments, status); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -187,15 +153,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalRealtimeResponseFunctionCallItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseFunctionCallItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeResponseFunctionCallItem)PersistableModelCreateCore(data, options); + protected override InternalRealtimeResponseItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseFunctionCallItem(document.RootElement, options); } default: @@ -205,15 +172,20 @@ InternalRealtimeResponseFunctionCallItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeResponseFunctionCallItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseFunctionCallItem internalRealtimeResponseFunctionCallItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseFunctionCallItem(document.RootElement); + if (internalRealtimeResponseFunctionCallItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseFunctionCallItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseFunctionCallItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseFunctionCallItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.cs b/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.cs index 7e39e744c..e1d10fa80 100644 --- a/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.cs +++ b/src/Generated/Models/InternalRealtimeResponseFunctionCallItem.cs @@ -9,20 +9,15 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseFunctionCallItem : InternalRealtimeResponseItem { - internal InternalRealtimeResponseFunctionCallItem(string id, string name, string callId, string arguments, ConversationItemStatus status) : base(id) + internal InternalRealtimeResponseFunctionCallItem(string id, string name, string callId, string arguments, ConversationItemStatus status) : base(InternalRealtimeItemType.FunctionCall, id) { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(callId, nameof(callId)); - Argument.AssertNotNull(arguments, nameof(arguments)); - - Type = InternalRealtimeItemType.FunctionCall; Name = name; CallId = callId; Arguments = arguments; Status = status; } - internal InternalRealtimeResponseFunctionCallItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, string name, string callId, string arguments, ConversationItemStatus status) : base(@object, type, id, serializedAdditionalRawData) + internal InternalRealtimeResponseFunctionCallItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, string name, string callId, string arguments, ConversationItemStatus status) : base(@object, @type, id, additionalBinaryDataProperties) { Name = name; CallId = callId; @@ -30,13 +25,12 @@ internal InternalRealtimeResponseFunctionCallItem(InternalRealtimeResponseItemOb Status = status; } - internal InternalRealtimeResponseFunctionCallItem() - { - } - public string Name { get; } + public string CallId { get; } + public string Arguments { get; } + public ConversationItemStatus Status { get; } } } diff --git a/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.Serialization.cs index e5fc5d5e0..c5b563a3d 100644 --- a/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.Serialization.cs @@ -7,153 +7,119 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseFunctionCallOutputItem : IJsonModel { + internal InternalRealtimeResponseFunctionCallOutputItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseFunctionCallOutputItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("output") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output") != true) { writer.WritePropertyName("output"u8); writer.WriteStringValue(Output); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - if (Id != null) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - else - { - writer.WriteNull("id"); - } - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeResponseFunctionCallOutputItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseFunctionCallOutputItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeResponseFunctionCallOutputItem)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeResponseItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseFunctionCallOutputItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseFunctionCallOutputItem(document.RootElement, options); } - internal static InternalRealtimeResponseFunctionCallOutputItem DeserializeInternalRealtimeResponseFunctionCallOutputItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseFunctionCallOutputItem DeserializeInternalRealtimeResponseFunctionCallOutputItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string callId = default; - string output = default; InternalRealtimeResponseItemObject @object = default; - InternalRealtimeItemType type = default; + InternalRealtimeItemType @type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string callId = default; + string output = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("object"u8)) { - callId = property.Value.GetString(); + @object = new InternalRealtimeResponseItemObject(prop.Value.GetString()); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("type"u8)) { - output = property.Value.GetString(); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalRealtimeResponseItemObject(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + id = null; + continue; + } + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("call_id"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("output"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - id = null; - continue; - } - id = property.Value.GetString(); + output = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeResponseFunctionCallOutputItem( @object, - type, + @type, id, - serializedAdditionalRawData, + additionalBinaryDataProperties, callId, output); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -163,15 +129,16 @@ BinaryData IPersistableModel.Wri } } - InternalRealtimeResponseFunctionCallOutputItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseFunctionCallOutputItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeResponseFunctionCallOutputItem)PersistableModelCreateCore(data, options); + protected override InternalRealtimeResponseItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseFunctionCallOutputItem(document.RootElement, options); } default: @@ -181,15 +148,20 @@ InternalRealtimeResponseFunctionCallOutputItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeResponseFunctionCallOutputItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseFunctionCallOutputItem internalRealtimeResponseFunctionCallOutputItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseFunctionCallOutputItem(document.RootElement); + if (internalRealtimeResponseFunctionCallOutputItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseFunctionCallOutputItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseFunctionCallOutputItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseFunctionCallOutputItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.cs b/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.cs index cca5a943e..7295ba6f7 100644 --- a/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.cs +++ b/src/Generated/Models/InternalRealtimeResponseFunctionCallOutputItem.cs @@ -9,27 +9,20 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseFunctionCallOutputItem : InternalRealtimeResponseItem { - internal InternalRealtimeResponseFunctionCallOutputItem(string id, string callId, string output) : base(id) + internal InternalRealtimeResponseFunctionCallOutputItem(string id, string callId, string output) : base(InternalRealtimeItemType.FunctionCallOutput, id) { - Argument.AssertNotNull(callId, nameof(callId)); - Argument.AssertNotNull(output, nameof(output)); - - Type = InternalRealtimeItemType.FunctionCallOutput; CallId = callId; Output = output; } - internal InternalRealtimeResponseFunctionCallOutputItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, string callId, string output) : base(@object, type, id, serializedAdditionalRawData) + internal InternalRealtimeResponseFunctionCallOutputItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, string callId, string output) : base(@object, @type, id, additionalBinaryDataProperties) { CallId = callId; Output = output; } - internal InternalRealtimeResponseFunctionCallOutputItem() - { - } - public string CallId { get; } + public string Output { get; } } } diff --git a/src/Generated/Models/InternalRealtimeResponseItem.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseItem.Serialization.cs index 3301880e3..8511388a3 100644 --- a/src/Generated/Models/InternalRealtimeResponseItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseItem.Serialization.cs @@ -6,32 +6,42 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeResponseItem))] - internal partial class InternalRealtimeResponseItem : IJsonModel + internal abstract partial class InternalRealtimeResponseItem : IJsonModel { + internal InternalRealtimeResponseItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { if (Id != null) { @@ -40,12 +50,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } else { - writer.WriteNull("id"); + writer.WriteNull("id"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,45 +72,47 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - InternalRealtimeResponseItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeResponseItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseItem(document.RootElement, options); } - internal static InternalRealtimeResponseItem DeserializeInternalRealtimeResponseItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseItem DeserializeInternalRealtimeResponseItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "function_call": return InternalRealtimeResponseFunctionCallItem.DeserializeInternalRealtimeResponseFunctionCallItem(element, options); - case "function_call_output": return InternalRealtimeResponseFunctionCallOutputItem.DeserializeInternalRealtimeResponseFunctionCallOutputItem(element, options); - case "message": return InternalRealtimeResponseMessageItem.DeserializeInternalRealtimeResponseMessageItem(element, options); + case "message": + return InternalRealtimeResponseMessageItem.DeserializeInternalRealtimeResponseMessageItem(element, options); + case "function_call": + return InternalRealtimeResponseFunctionCallItem.DeserializeInternalRealtimeResponseFunctionCallItem(element, options); + case "function_call_output": + return InternalRealtimeResponseFunctionCallOutputItem.DeserializeInternalRealtimeResponseFunctionCallOutputItem(element, options); } } return UnknownRealtimeResponseItem.DeserializeUnknownRealtimeResponseItem(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -110,15 +122,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalRealtimeResponseItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeResponseItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseItem(document.RootElement, options); } default: @@ -128,15 +141,20 @@ InternalRealtimeResponseItem IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeResponseItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseItem internalRealtimeResponseItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseItem(document.RootElement); + if (internalRealtimeResponseItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseItem, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseItem.cs b/src/Generated/Models/InternalRealtimeResponseItem.cs index 09bd77adc..a8ed46d55 100644 --- a/src/Generated/Models/InternalRealtimeResponseItem.cs +++ b/src/Generated/Models/InternalRealtimeResponseItem.cs @@ -9,27 +9,32 @@ namespace OpenAI.RealtimeConversation { internal abstract partial class InternalRealtimeResponseItem { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalRealtimeResponseItem(string id) + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalRealtimeResponseItem(InternalRealtimeItemType @type, string id) { + Type = @type; Id = id; } - internal InternalRealtimeResponseItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData) + internal InternalRealtimeResponseItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties) { Object = @object; - Type = type; + Type = @type; Id = id; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRealtimeResponseItem() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalRealtimeResponseItemObject Object { get; } = InternalRealtimeResponseItemObject.RealtimeItem; + public InternalRealtimeResponseItemObject Object { get; } = "realtime.item"; internal InternalRealtimeItemType Type { get; set; } + public string Id { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeResponseItemObject.cs b/src/Generated/Models/InternalRealtimeResponseItemObject.cs index fed455fcd..d5c5d6c55 100644 --- a/src/Generated/Models/InternalRealtimeResponseItemObject.cs +++ b/src/Generated/Models/InternalRealtimeResponseItemObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeResponseItemObject : IEquatable { private readonly string _value; + private const string RealtimeItemValue = "realtime.item"; public InternalRealtimeResponseItemObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string RealtimeItemValue = "realtime.item"; + _value = value; + } public static InternalRealtimeResponseItemObject RealtimeItem { get; } = new InternalRealtimeResponseItemObject(RealtimeItemValue); + public static bool operator ==(InternalRealtimeResponseItemObject left, InternalRealtimeResponseItemObject right) => left.Equals(right); + public static bool operator !=(InternalRealtimeResponseItemObject left, InternalRealtimeResponseItemObject right) => !left.Equals(right); + public static implicit operator InternalRealtimeResponseItemObject(string value) => new InternalRealtimeResponseItemObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeResponseItemObject other && Equals(other); + public bool Equals(InternalRealtimeResponseItemObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeResponseMessageItem.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseMessageItem.Serialization.cs index bc558a0fa..fc7df83e3 100644 --- a/src/Generated/Models/InternalRealtimeResponseMessageItem.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseMessageItem.Serialization.cs @@ -7,175 +7,141 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseMessageItem : IJsonModel { + internal InternalRealtimeResponseMessageItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseMessageItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("content") != true) + base.JsonModelWriteCore(writer, options); + if (true && _additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (ConversationContentPart item in Content) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) { - if (Id != null) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - else - { - writer.WriteNull("id"); - } - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); } - writer.WriteEndObject(); } - InternalRealtimeResponseMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeResponseMessageItem)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeResponseItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseMessageItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseMessageItem(document.RootElement, options); } - internal static InternalRealtimeResponseMessageItem DeserializeInternalRealtimeResponseMessageItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseMessageItem DeserializeInternalRealtimeResponseMessageItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationMessageRole role = default; - IReadOnlyList content = default; - ConversationItemStatus status = default; InternalRealtimeResponseItemObject @object = default; - InternalRealtimeItemType type = default; + InternalRealtimeItemType @type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + IReadOnlyList content = default; + ConversationItemStatus status = default; + ConversationMessageRole role = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) + if (prop.NameEquals("object"u8)) { - role = new ConversationMessageRole(property.Value.GetString()); + @object = new InternalRealtimeResponseItemObject(prop.Value.GetString()); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("type"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); - } - content = array; + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("id"u8)) { - status = new ConversationItemStatus(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + id = null; + continue; + } + id = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("content"u8)) { - @object = new InternalRealtimeResponseItemObject(property.Value.GetString()); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ConversationContentPart.DeserializeConversationContentPart(item, options)); + } + content = array; continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("status"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + status = new ConversationItemStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - id = null; - continue; - } - id = property.Value.GetString(); + role = new ConversationMessageRole(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeResponseMessageItem( @object, - type, + @type, id, - serializedAdditionalRawData, - role, + additionalBinaryDataProperties, content, - status); + status, + role); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -185,15 +151,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - InternalRealtimeResponseMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeResponseMessageItem)PersistableModelCreateCore(data, options); + protected override InternalRealtimeResponseItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseMessageItem(document.RootElement, options); } default: @@ -203,15 +170,20 @@ InternalRealtimeResponseMessageItem IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeResponseMessageItem FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseMessageItem internalRealtimeResponseMessageItem) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseMessageItem(document.RootElement); + if (internalRealtimeResponseMessageItem == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseMessageItem, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseMessageItem(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseMessageItem(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseMessageItem.cs b/src/Generated/Models/InternalRealtimeResponseMessageItem.cs index e890da2f5..827580df0 100644 --- a/src/Generated/Models/InternalRealtimeResponseMessageItem.cs +++ b/src/Generated/Models/InternalRealtimeResponseMessageItem.cs @@ -4,33 +4,28 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseMessageItem : InternalRealtimeResponseItem { - internal InternalRealtimeResponseMessageItem(string id, ConversationMessageRole role, IEnumerable content, ConversationItemStatus status) : base(id) + internal InternalRealtimeResponseMessageItem(string id, ConversationItemStatus status, ConversationMessageRole role) : base(InternalRealtimeItemType.Message, id) { - Argument.AssertNotNull(content, nameof(content)); - - Type = InternalRealtimeItemType.Message; - Role = role; - Content = content.ToList(); + Content = new ChangeTrackingList(); Status = status; + Role = role; } - internal InternalRealtimeResponseMessageItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData, ConversationMessageRole role, IReadOnlyList content, ConversationItemStatus status) : base(@object, type, id, serializedAdditionalRawData) + internal InternalRealtimeResponseMessageItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, IReadOnlyList content, ConversationItemStatus status, ConversationMessageRole role) : base(@object, @type, id, additionalBinaryDataProperties) { - Role = role; Content = content; Status = status; + Role = role; } - internal InternalRealtimeResponseMessageItem() - { - } public IReadOnlyList Content { get; } + public ConversationItemStatus Status { get; } } } diff --git a/src/Generated/Models/InternalRealtimeResponseObject.cs b/src/Generated/Models/InternalRealtimeResponseObject.cs index 66f2080fc..113343549 100644 --- a/src/Generated/Models/InternalRealtimeResponseObject.cs +++ b/src/Generated/Models/InternalRealtimeResponseObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeResponseObject : IEquatable { private readonly string _value; + private const string RealtimeResponseValue = "realtime.response"; public InternalRealtimeResponseObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string RealtimeResponseValue = "realtime.response"; + _value = value; + } public static InternalRealtimeResponseObject RealtimeResponse { get; } = new InternalRealtimeResponseObject(RealtimeResponseValue); + public static bool operator ==(InternalRealtimeResponseObject left, InternalRealtimeResponseObject right) => left.Equals(right); + public static bool operator !=(InternalRealtimeResponseObject left, InternalRealtimeResponseObject right) => !left.Equals(right); + public static implicit operator InternalRealtimeResponseObject(string value) => new InternalRealtimeResponseObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeResponseObject other && Equals(other); + public bool Equals(InternalRealtimeResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeResponseSession.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseSession.Serialization.cs index 97459c6fb..8b2c39d1c 100644 --- a/src/Generated/Models/InternalRealtimeResponseSession.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseSession.Serialization.cs @@ -7,66 +7,76 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseSession : IJsonModel { + internal InternalRealtimeResponseSession() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseSession)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("modalities") != true) + if (_additionalBinaryDataProperties?.ContainsKey("modalities") != true) { writer.WritePropertyName("modalities"u8); writer.WriteStartArray(); - foreach (var item in Modalities) + foreach (InternalRealtimeRequestSessionModality item in Modalities) { writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("instructions") != true) { writer.WritePropertyName("instructions"u8); writer.WriteStringValue(Instructions); } - if (SerializedAdditionalRawData?.ContainsKey("voice") != true) + if (_additionalBinaryDataProperties?.ContainsKey("voice") != true) { writer.WritePropertyName("voice"u8); writer.WriteStringValue(Voice.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("input_audio_format") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_audio_format") != true) { writer.WritePropertyName("input_audio_format"u8); writer.WriteStringValue(InputAudioFormat.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("output_audio_format") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_audio_format") != true) { writer.WritePropertyName("output_audio_format"u8); writer.WriteStringValue(OutputAudioFormat.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("input_audio_transcription") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input_audio_transcription") != true) { if (InputAudioTranscription != null) { @@ -75,29 +85,29 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("input_audio_transcription"); + writer.WriteNull("inputAudioTranscription"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("turn_detection") != true) + if (_additionalBinaryDataProperties?.ContainsKey("turn_detection") != true) { writer.WritePropertyName("turn_detection"u8); writer.WriteObjectValue(TurnDetection, options); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ConversationTool item in Tools) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true) + if (_additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { writer.WritePropertyName("tool_choice"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(ToolChoice); + writer.WriteRawValue(ToolChoice); #else using (JsonDocument document = JsonDocument.Parse(ToolChoice)) { @@ -105,18 +115,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } #endif } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true) + if (_additionalBinaryDataProperties?.ContainsKey("temperature") != true) { writer.WritePropertyName("temperature"u8); writer.WriteNumberValue(Temperature); } - if (SerializedAdditionalRawData?.ContainsKey("max_response_output_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("max_response_output_tokens") != true) { if (_maxResponseOutputTokens != null) { writer.WritePropertyName("max_response_output_tokens"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(_maxResponseOutputTokens); + writer.WriteRawValue(_maxResponseOutputTokens); #else using (JsonDocument document = JsonDocument.Parse(_maxResponseOutputTokens)) { @@ -126,12 +136,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } else { - writer.WriteNull("max_response_output_tokens"); + writer.WriteNull("maxResponseOutputTokens"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -139,7 +149,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -148,25 +158,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalRealtimeResponseSession IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseSession IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeResponseSession JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseSession)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseSession(document.RootElement, options); } - internal static InternalRealtimeResponseSession DeserializeInternalRealtimeResponseSession(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseSession DeserializeInternalRealtimeResponseSession(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -174,7 +182,7 @@ internal static InternalRealtimeResponseSession DeserializeInternalRealtimeRespo InternalRealtimeResponseSessionObject @object = default; string id = default; string model = default; - IReadOnlyList modalities = default; + IList modalities = default; string instructions = default; ConversationVoice voice = default; ConversationAudioFormat inputAudioFormat = default; @@ -185,107 +193,104 @@ internal static InternalRealtimeResponseSession DeserializeInternalRealtimeRespo BinaryData toolChoice = default; float temperature = default; BinaryData maxResponseOutputTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalRealtimeResponseSessionObject(property.Value.GetString()); + @object = new InternalRealtimeResponseSessionObject(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("modalities"u8)) + if (prop.NameEquals("modalities"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(new InternalRealtimeRequestSessionModality(item.GetString())); } modalities = array; continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("voice"u8)) + if (prop.NameEquals("voice"u8)) { - voice = new ConversationVoice(property.Value.GetString()); + voice = new ConversationVoice(prop.Value.GetString()); continue; } - if (property.NameEquals("input_audio_format"u8)) + if (prop.NameEquals("input_audio_format"u8)) { - inputAudioFormat = new ConversationAudioFormat(property.Value.GetString()); + inputAudioFormat = new ConversationAudioFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("output_audio_format"u8)) + if (prop.NameEquals("output_audio_format"u8)) { - outputAudioFormat = new ConversationAudioFormat(property.Value.GetString()); + outputAudioFormat = new ConversationAudioFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("input_audio_transcription"u8)) + if (prop.NameEquals("input_audio_transcription"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { inputAudioTranscription = null; continue; } - inputAudioTranscription = ConversationInputTranscriptionOptions.DeserializeConversationInputTranscriptionOptions(property.Value, options); + inputAudioTranscription = ConversationInputTranscriptionOptions.DeserializeConversationInputTranscriptionOptions(prop.Value, options); continue; } - if (property.NameEquals("turn_detection"u8)) + if (prop.NameEquals("turn_detection"u8)) { - turnDetection = ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(property.Value, options); + turnDetection = ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(prop.Value, options); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ConversationTool.DeserializeConversationTool(item, options)); } tools = array; continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("tool_choice"u8)) { - toolChoice = BinaryData.FromString(property.Value.GetRawText()); + toolChoice = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("max_response_output_tokens"u8)) + if (prop.NameEquals("max_response_output_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { maxResponseOutputTokens = null; continue; } - maxResponseOutputTokens = BinaryData.FromString(property.Value.GetRawText()); + maxResponseOutputTokens = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeResponseSession( @object, id, @@ -301,13 +306,14 @@ internal static InternalRealtimeResponseSession DeserializeInternalRealtimeRespo toolChoice, temperature, maxResponseOutputTokens, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -317,15 +323,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalRealtimeResponseSession IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseSession IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeResponseSession 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseSession(document.RootElement, options); } default: @@ -335,15 +342,20 @@ InternalRealtimeResponseSession IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeResponseSession FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseSession internalRealtimeResponseSession) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseSession(document.RootElement); + if (internalRealtimeResponseSession == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseSession, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseSession(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseSession(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseSession.cs b/src/Generated/Models/InternalRealtimeResponseSession.cs index 50a7fa482..f6eb7e92a 100644 --- a/src/Generated/Models/InternalRealtimeResponseSession.cs +++ b/src/Generated/Models/InternalRealtimeResponseSession.cs @@ -5,22 +5,16 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseSession { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal InternalRealtimeResponseSession(string id, string model, IEnumerable modalities, string instructions, ConversationVoice voice, ConversationAudioFormat inputAudioFormat, ConversationAudioFormat outputAudioFormat, ConversationInputTranscriptionOptions inputAudioTranscription, ConversationTurnDetectionOptions turnDetection, IEnumerable tools, BinaryData toolChoice, float temperature, BinaryData maxResponseOutputTokens) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(model, nameof(model)); - Argument.AssertNotNull(modalities, nameof(modalities)); - Argument.AssertNotNull(instructions, nameof(instructions)); - Argument.AssertNotNull(turnDetection, nameof(turnDetection)); - Argument.AssertNotNull(tools, nameof(tools)); - Argument.AssertNotNull(toolChoice, nameof(toolChoice)); + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRealtimeResponseSession(string id, string model, IEnumerable modalities, string instructions, ConversationVoice voice, ConversationAudioFormat inputAudioFormat, ConversationAudioFormat outputAudioFormat, ConversationInputTranscriptionOptions inputAudioTranscription, ConversationTurnDetectionOptions turnDetection, BinaryData toolChoice, float temperature, BinaryData maxResponseOutputTokens) + { Id = id; Model = model; Modalities = modalities.ToList(); @@ -30,13 +24,13 @@ internal InternalRealtimeResponseSession(string id, string model, IEnumerable(); ToolChoice = toolChoice; Temperature = temperature; _maxResponseOutputTokens = maxResponseOutputTokens; } - internal InternalRealtimeResponseSession(InternalRealtimeResponseSessionObject @object, string id, string model, IReadOnlyList modalities, string instructions, ConversationVoice voice, ConversationAudioFormat inputAudioFormat, ConversationAudioFormat outputAudioFormat, ConversationInputTranscriptionOptions inputAudioTranscription, ConversationTurnDetectionOptions turnDetection, IReadOnlyList tools, BinaryData toolChoice, float temperature, BinaryData maxResponseOutputTokens, IDictionary serializedAdditionalRawData) + internal InternalRealtimeResponseSession(InternalRealtimeResponseSessionObject @object, string id, string model, IList modalities, string instructions, ConversationVoice voice, ConversationAudioFormat inputAudioFormat, ConversationAudioFormat outputAudioFormat, ConversationInputTranscriptionOptions inputAudioTranscription, ConversationTurnDetectionOptions turnDetection, IReadOnlyList tools, BinaryData toolChoice, float temperature, BinaryData maxResponseOutputTokens, IDictionary additionalBinaryDataProperties) { Object = @object; Id = id; @@ -52,26 +46,39 @@ internal InternalRealtimeResponseSession(InternalRealtimeResponseSessionObject @ ToolChoice = toolChoice; Temperature = temperature; _maxResponseOutputTokens = maxResponseOutputTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRealtimeResponseSession() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalRealtimeResponseSessionObject Object { get; } = InternalRealtimeResponseSessionObject.RealtimeSession; + public InternalRealtimeResponseSessionObject Object { get; } = "realtime.session"; public string Id { get; } + public string Model { get; } - public IReadOnlyList Modalities { get; } + + public IList Modalities { get; } + public string Instructions { get; } + public ConversationVoice Voice { get; } + public ConversationAudioFormat InputAudioFormat { get; } + public ConversationAudioFormat OutputAudioFormat { get; } + public ConversationInputTranscriptionOptions InputAudioTranscription { get; } + public ConversationTurnDetectionOptions TurnDetection { get; } + public IReadOnlyList Tools { get; } + public BinaryData ToolChoice { get; } + public float Temperature { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeResponseSessionObject.cs b/src/Generated/Models/InternalRealtimeResponseSessionObject.cs index 0ebab772a..e73181f01 100644 --- a/src/Generated/Models/InternalRealtimeResponseSessionObject.cs +++ b/src/Generated/Models/InternalRealtimeResponseSessionObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.RealtimeConversation { internal readonly partial struct InternalRealtimeResponseSessionObject : IEquatable { private readonly string _value; + private const string RealtimeSessionValue = "realtime.session"; public InternalRealtimeResponseSessionObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string RealtimeSessionValue = "realtime.session"; + _value = value; + } public static InternalRealtimeResponseSessionObject RealtimeSession { get; } = new InternalRealtimeResponseSessionObject(RealtimeSessionValue); + public static bool operator ==(InternalRealtimeResponseSessionObject left, InternalRealtimeResponseSessionObject right) => left.Equals(right); + public static bool operator !=(InternalRealtimeResponseSessionObject left, InternalRealtimeResponseSessionObject right) => !left.Equals(right); + public static implicit operator InternalRealtimeResponseSessionObject(string value) => new InternalRealtimeResponseSessionObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRealtimeResponseSessionObject other && Equals(other); + public bool Equals(InternalRealtimeResponseSessionObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRealtimeResponseTextContentPart.Serialization.cs b/src/Generated/Models/InternalRealtimeResponseTextContentPart.Serialization.cs index d757cd9e5..bc533f6ba 100644 --- a/src/Generated/Models/InternalRealtimeResponseTextContentPart.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeResponseTextContentPart.Serialization.cs @@ -7,113 +7,96 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseTextContentPart : IJsonModel { + internal InternalRealtimeResponseTextContentPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseTextContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(InternalTextValue); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeResponseTextContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseTextContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeResponseTextContentPart)JsonModelCreateCore(ref reader, options); + + protected override ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseTextContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseTextContentPart(document.RootElement, options); } - internal static InternalRealtimeResponseTextContentPart DeserializeInternalRealtimeResponseTextContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeResponseTextContentPart DeserializeInternalRealtimeResponseTextContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - string text = default; - ConversationContentPartKind type0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPartKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = "text"; + string internalTextValue = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + kind = new ConversationContentPartKind(prop.Value.GetString()); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("type"u8)) { - text = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("text"u8)) { - type0 = new ConversationContentPartKind(property.Value.GetString()); + internalTextValue = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeResponseTextContentPart(type0, serializedAdditionalRawData, type, text); + return new InternalRealtimeResponseTextContentPart(kind, additionalBinaryDataProperties, @type, internalTextValue); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +106,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalRealtimeResponseTextContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseTextContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeResponseTextContentPart)PersistableModelCreateCore(data, options); + protected override ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseTextContentPart(document.RootElement, options); } default: @@ -141,15 +125,20 @@ InternalRealtimeResponseTextContentPart IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeResponseTextContentPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeResponseTextContentPart internalRealtimeResponseTextContentPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeResponseTextContentPart(document.RootElement); + if (internalRealtimeResponseTextContentPart == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeResponseTextContentPart, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeResponseTextContentPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeResponseTextContentPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeResponseTextContentPart.cs b/src/Generated/Models/InternalRealtimeResponseTextContentPart.cs index 133432b64..ea8649803 100644 --- a/src/Generated/Models/InternalRealtimeResponseTextContentPart.cs +++ b/src/Generated/Models/InternalRealtimeResponseTextContentPart.cs @@ -9,24 +9,17 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeResponseTextContentPart : ConversationContentPart { - internal InternalRealtimeResponseTextContentPart(string internalTextValue) + internal InternalRealtimeResponseTextContentPart(string internalTextValue) : base(ConversationContentPartKind.OutputText) { - Argument.AssertNotNull(internalTextValue, nameof(internalTextValue)); - - Kind = ConversationContentPartKind.OutputText; InternalTextValue = internalTextValue; } - internal InternalRealtimeResponseTextContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData, string type, string internalTextValue) : base(kind, serializedAdditionalRawData) + internal InternalRealtimeResponseTextContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties, string @type, string internalTextValue) : base(kind, additionalBinaryDataProperties) { - Type = type; + Type = @type; InternalTextValue = internalTextValue; } - internal InternalRealtimeResponseTextContentPart() - { - } - internal string Type { get; set; } = "text"; } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationCreated.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventConversationCreated.Serialization.cs index d1413892a..1703b7bb4 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationCreated.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationCreated.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventConversationCreated : IJsonModel { + internal InternalRealtimeServerEventConversationCreated() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventConversationCreated)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("conversation") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("conversation") != true) { writer.WritePropertyName("conversation"u8); writer.WriteObjectValue(Conversation, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventConversationCreated IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventConversationCreated IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventConversationCreated)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventConversationCreated)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventConversationCreated(document.RootElement, options); } - internal static InternalRealtimeServerEventConversationCreated DeserializeInternalRealtimeServerEventConversationCreated(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventConversationCreated DeserializeInternalRealtimeServerEventConversationCreated(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeServerEventConversationCreatedConversation conversation = default; - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRealtimeServerEventConversationCreatedConversation conversation = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("conversation"u8)) + if (prop.NameEquals("event_id"u8)) { - conversation = InternalRealtimeServerEventConversationCreatedConversation.DeserializeInternalRealtimeServerEventConversationCreatedConversation(property.Value, options); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("conversation"u8)) { - eventId = property.Value.GetString(); + conversation = InternalRealtimeServerEventConversationCreatedConversation.DeserializeInternalRealtimeServerEventConversationCreatedConversation(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeServerEventConversationCreated(type, eventId, serializedAdditionalRawData, conversation); + return new InternalRealtimeServerEventConversationCreated(eventId, kind, additionalBinaryDataProperties, conversation); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Wri } } - InternalRealtimeServerEventConversationCreated IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventConversationCreated IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventConversationCreated)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventConversationCreated(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRealtimeServerEventConversationCreated IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventConversationCreated FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventConversationCreated internalRealtimeServerEventConversationCreated) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventConversationCreated(document.RootElement); + if (internalRealtimeServerEventConversationCreated == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventConversationCreated, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventConversationCreated(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventConversationCreated(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationCreated.cs b/src/Generated/Models/InternalRealtimeServerEventConversationCreated.cs index f992de4a3..7ab1726b1 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationCreated.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationCreated.cs @@ -9,24 +9,16 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventConversationCreated : ConversationUpdate { - internal InternalRealtimeServerEventConversationCreated(string eventId, InternalRealtimeServerEventConversationCreatedConversation conversation) : base(eventId) + internal InternalRealtimeServerEventConversationCreated(string eventId, InternalRealtimeServerEventConversationCreatedConversation conversation) : base(eventId, RealtimeConversation.ConversationUpdateKind.ConversationCreated) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(conversation, nameof(conversation)); - - Kind = ConversationUpdateKind.ConversationCreated; Conversation = conversation; } - internal InternalRealtimeServerEventConversationCreated(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, InternalRealtimeServerEventConversationCreatedConversation conversation) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventConversationCreated(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, InternalRealtimeServerEventConversationCreatedConversation conversation) : base(eventId, kind, additionalBinaryDataProperties) { Conversation = conversation; } - internal InternalRealtimeServerEventConversationCreated() - { - } - public InternalRealtimeServerEventConversationCreatedConversation Conversation { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.Serialization.cs index b818ebd70..8ece57ae1 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,26 +15,31 @@ internal partial class InternalRealtimeServerEventConversationCreatedConversatio { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventConversationCreatedConversation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true && Optional.IsDefined(Object)) + if (Optional.IsDefined(Object) && _additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Writ #endif } } - writer.WriteEndObject(); } - InternalRealtimeServerEventConversationCreatedConversation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventConversationCreatedConversation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeServerEventConversationCreatedConversation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventConversationCreatedConversation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventConversationCreatedConversation(document.RootElement, options); } - internal static InternalRealtimeServerEventConversationCreatedConversation DeserializeInternalRealtimeServerEventConversationCreatedConversation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventConversationCreatedConversation DeserializeInternalRealtimeServerEventConversationCreatedConversation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; string @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = property.Value.GetString(); + @object = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeServerEventConversationCreatedConversation(id, @object, serializedAdditionalRawData); + return new InternalRealtimeServerEventConversationCreatedConversation(id, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventConversationCreatedConversation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeServerEventConversationCreatedConversation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventConversationCreatedConversation(document.RootElement, options); } default: @@ -130,15 +133,20 @@ InternalRealtimeServerEventConversationCreatedConversation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeServerEventConversationCreatedConversation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventConversationCreatedConversation internalRealtimeServerEventConversationCreatedConversation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventConversationCreatedConversation(document.RootElement); + if (internalRealtimeServerEventConversationCreatedConversation == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventConversationCreatedConversation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventConversationCreatedConversation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventConversationCreatedConversation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.cs b/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.cs index 519df281e..53ad76b45 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationCreatedConversation.cs @@ -9,19 +9,27 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventConversationCreatedConversation { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRealtimeServerEventConversationCreatedConversation() { } - internal InternalRealtimeServerEventConversationCreatedConversation(string id, string @object, IDictionary serializedAdditionalRawData) + internal InternalRealtimeServerEventConversationCreatedConversation(string id, string @object, IDictionary additionalBinaryDataProperties) { Id = id; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public string Object { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.Serialization.cs index 67d2b6611..be0d12086 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,36 +15,41 @@ internal partial class InternalRealtimeServerEventConversationItemInputAudioTran { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) + if (Optional.IsDefined(Type) && _additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) + if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) + if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("param") != true && Optional.IsDefined(Param)) + if (Optional.IsDefined(Param) && _additionalBinaryDataProperties?.ContainsKey("param") != true) { writer.WritePropertyName("param"u8); writer.WriteStringValue(Param); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +57,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(document.RootElement, options); } - internal static InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; + string @type = default; string code = default; string message = default; - string param = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @param = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("param"u8)) + if (prop.NameEquals("param"u8)) { - param = property.Value.GetString(); + @param = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(type, code, message, param, serializedAdditionalRawData); + return new InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(@type, code, message, @param, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +136,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(document.RootElement, options); } default: @@ -152,15 +155,20 @@ InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError IP string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError internalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(document.RootElement); + if (internalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.cs b/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.cs index 4a79d144f..f760303d7 100644 --- a/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.cs +++ b/src/Generated/Models/InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError.cs @@ -9,23 +9,33 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError() { } - internal InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(string type, string code, string message, string param, IDictionary serializedAdditionalRawData) + internal InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError(string @type, string code, string message, string @param, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Code = code; Message = message; - Param = param; - SerializedAdditionalRawData = serializedAdditionalRawData; + Param = @param; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Type { get; } + public string Code { get; } + public string Message { get; } + public string Param { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventErrorError.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventErrorError.Serialization.cs index 4274ac51e..b9180e740 100644 --- a/src/Generated/Models/InternalRealtimeServerEventErrorError.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventErrorError.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,41 +15,46 @@ internal partial class InternalRealtimeServerEventErrorError : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventErrorError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) + if (Optional.IsDefined(Type) && _additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) + if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) + if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("param") != true && Optional.IsDefined(Param)) + if (Optional.IsDefined(Param) && _additionalBinaryDataProperties?.ContainsKey("param") != true) { writer.WritePropertyName("param"u8); writer.WriteStringValue(Param); } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) + if (Optional.IsDefined(EventId) && _additionalBinaryDataProperties?.ContainsKey("event_id") != true) { writer.WritePropertyName("event_id"u8); writer.WriteStringValue(EventId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +62,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,83 +71,79 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalRealtimeServerEventErrorError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventErrorError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeServerEventErrorError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventErrorError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventErrorError(document.RootElement, options); } - internal static InternalRealtimeServerEventErrorError DeserializeInternalRealtimeServerEventErrorError(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventErrorError DeserializeInternalRealtimeServerEventErrorError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; + string @type = default; string code = default; string message = default; - string param = default; + string @param = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("param"u8)) + if (prop.NameEquals("param"u8)) { - param = property.Value.GetString(); + @param = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("event_id"u8)) { - eventId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventErrorError( - type, + @type, code, message, - param, + @param, eventId, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +153,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalRealtimeServerEventErrorError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventErrorError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeServerEventErrorError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventErrorError(document.RootElement, options); } default: @@ -169,15 +172,20 @@ InternalRealtimeServerEventErrorError IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeServerEventErrorError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventErrorError internalRealtimeServerEventErrorError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventErrorError(document.RootElement); + if (internalRealtimeServerEventErrorError == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventErrorError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventErrorError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventErrorError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventErrorError.cs b/src/Generated/Models/InternalRealtimeServerEventErrorError.cs index b0d420eaa..41498342f 100644 --- a/src/Generated/Models/InternalRealtimeServerEventErrorError.cs +++ b/src/Generated/Models/InternalRealtimeServerEventErrorError.cs @@ -9,25 +9,36 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventErrorError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRealtimeServerEventErrorError() { } - internal InternalRealtimeServerEventErrorError(string type, string code, string message, string param, string eventId, IDictionary serializedAdditionalRawData) + internal InternalRealtimeServerEventErrorError(string @type, string code, string message, string @param, string eventId, IDictionary additionalBinaryDataProperties) { - Type = type; + Type = @type; Code = code; Message = message; - Param = param; + Param = @param; EventId = eventId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Type { get; } + public string Code { get; } + public string Message { get; } + public string Param { get; } + public string EventId { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.Serialization.cs index d9fa4e276..1628ee0f0 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseAudioDelta : IJsonModel { + internal InternalRealtimeServerEventResponseAudioDelta() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseAudioDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteBase64StringValue(Delta.ToArray(), "D"); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseAudioDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseAudioDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseAudioDelta)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseAudioDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseAudioDelta(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseAudioDelta DeserializeInternalRealtimeServerEventResponseAudioDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseAudioDelta DeserializeInternalRealtimeServerEventResponseAudioDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; BinaryData delta = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("output_index"u8)) { - delta = BinaryData.FromBytes(property.Value.GetBytesFromBase64("D")); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("delta"u8)) { - eventId = property.Value.GetString(); + delta = BinaryData.FromBytes(prop.Value.GetBytesFromBase64("D")); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseAudioDelta( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static InternalRealtimeServerEventResponseAudioDelta DeserializeInterna delta); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Writ } } - InternalRealtimeServerEventResponseAudioDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseAudioDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseAudioDelta)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseAudioDelta(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseAudioDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseAudioDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseAudioDelta internalRealtimeServerEventResponseAudioDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseAudioDelta(document.RootElement); + if (internalRealtimeServerEventResponseAudioDelta == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseAudioDelta, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseAudioDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseAudioDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.cs b/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.cs index 88d7c6c92..0008ec7db 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseAudioDelta.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseAudioDelta : ConversationUpdate { - internal InternalRealtimeServerEventResponseAudioDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, BinaryData delta) : base(eventId) + internal InternalRealtimeServerEventResponseAudioDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, BinaryData delta) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioDelta) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(delta, nameof(delta)); - - Kind = ConversationUpdateKind.ItemStreamingPartAudioDelta; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal InternalRealtimeServerEventResponseAudioDelta(string eventId, string re Delta = delta; } - internal InternalRealtimeServerEventResponseAudioDelta(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, BinaryData delta) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseAudioDelta(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, BinaryData delta) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,14 +27,14 @@ internal InternalRealtimeServerEventResponseAudioDelta(ConversationUpdateKind ki Delta = delta; } - internal InternalRealtimeServerEventResponseAudioDelta() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } + public BinaryData Delta { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.Serialization.cs index dd5b6ec91..19f21c807 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseAudioTranscriptDelta : IJsonModel { + internal InternalRealtimeServerEventResponseAudioTranscriptDelta() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseAudioTranscriptDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteStringValue(Delta); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseAudioTranscriptDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseAudioTranscriptDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseAudioTranscriptDelta)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseAudioTranscriptDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseAudioTranscriptDelta DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseAudioTranscriptDelta DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; string delta = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("output_index"u8)) { - delta = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("delta"u8)) { - eventId = property.Value.GetString(); + delta = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseAudioTranscriptDelta( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static InternalRealtimeServerEventResponseAudioTranscriptDelta Deserial delta); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseAudioTranscriptDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseAudioTranscriptDelta)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseAudioTranscriptDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseAudioTranscriptDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseAudioTranscriptDelta internalRealtimeServerEventResponseAudioTranscriptDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(document.RootElement); + if (internalRealtimeServerEventResponseAudioTranscriptDelta == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseAudioTranscriptDelta, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseAudioTranscriptDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseAudioTranscriptDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.cs b/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.cs index 6524a40b1..e85f7e786 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseAudioTranscriptDelta.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseAudioTranscriptDelta : ConversationUpdate { - internal InternalRealtimeServerEventResponseAudioTranscriptDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId) + internal InternalRealtimeServerEventResponseAudioTranscriptDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioTranscriptionDelta) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(delta, nameof(delta)); - - Kind = ConversationUpdateKind.ItemStreamingPartAudioTranscriptionDelta; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal InternalRealtimeServerEventResponseAudioTranscriptDelta(string eventId, Delta = delta; } - internal InternalRealtimeServerEventResponseAudioTranscriptDelta(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseAudioTranscriptDelta(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,14 +27,14 @@ internal InternalRealtimeServerEventResponseAudioTranscriptDelta(ConversationUpd Delta = delta; } - internal InternalRealtimeServerEventResponseAudioTranscriptDelta() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } + public string Delta { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.Serialization.cs index 058d05450..8c138a43c 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.Serialization.cs @@ -7,165 +7,143 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseContentPartAdded : IJsonModel { + internal InternalRealtimeServerEventResponseContentPartAdded() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseContentPartAdded)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("part") != true) + if (_additionalBinaryDataProperties?.ContainsKey("part") != true) { writer.WritePropertyName("part"u8); writer.WriteObjectValue(_internalContentPart, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseContentPartAdded IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseContentPartAdded IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseContentPartAdded)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseContentPartAdded)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseContentPartAdded(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseContentPartAdded DeserializeInternalRealtimeServerEventResponseContentPartAdded(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseContentPartAdded DeserializeInternalRealtimeServerEventResponseContentPartAdded(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; - ConversationContentPart part = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPart internalContentPart = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("part"u8)) + if (prop.NameEquals("output_index"u8)) { - part = ConversationContentPart.DeserializeConversationContentPart(property.Value, options); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("part"u8)) { - eventId = property.Value.GetString(); + internalContentPart = ConversationContentPart.DeserializeConversationContentPart(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseContentPartAdded( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, contentIndex, - part); + internalContentPart); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseContentPartAdded IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseContentPartAdded)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseContentPartAdded(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseContentPartAdded IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseContentPartAdded FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseContentPartAdded internalRealtimeServerEventResponseContentPartAdded) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseContentPartAdded(document.RootElement); + if (internalRealtimeServerEventResponseContentPartAdded == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseContentPartAdded, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseContentPartAdded(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseContentPartAdded(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.cs b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.cs index 9d6249292..724642f3a 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartAdded.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseContentPartAdded : ConversationUpdate { - internal InternalRealtimeServerEventResponseContentPartAdded(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId) + internal InternalRealtimeServerEventResponseContentPartAdded(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemContentPartStarted) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(internalContentPart, nameof(internalContentPart)); - - Kind = ConversationUpdateKind.ItemContentPartStarted; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal InternalRealtimeServerEventResponseContentPartAdded(string eventId, str _internalContentPart = internalContentPart; } - internal InternalRealtimeServerEventResponseContentPartAdded(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseContentPartAdded(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,13 +27,12 @@ internal InternalRealtimeServerEventResponseContentPartAdded(ConversationUpdateK _internalContentPart = internalContentPart; } - internal InternalRealtimeServerEventResponseContentPartAdded() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.Serialization.cs index 28f8dfafc..692b849de 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.Serialization.cs @@ -7,165 +7,143 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseContentPartDone : IJsonModel { + internal InternalRealtimeServerEventResponseContentPartDone() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseContentPartDone)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("part") != true) + if (_additionalBinaryDataProperties?.ContainsKey("part") != true) { writer.WritePropertyName("part"u8); writer.WriteObjectValue(_internalContentPart, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseContentPartDone IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseContentPartDone IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseContentPartDone)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseContentPartDone)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseContentPartDone(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseContentPartDone DeserializeInternalRealtimeServerEventResponseContentPartDone(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseContentPartDone DeserializeInternalRealtimeServerEventResponseContentPartDone(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; - ConversationContentPart part = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPart internalContentPart = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("part"u8)) + if (prop.NameEquals("output_index"u8)) { - part = ConversationContentPart.DeserializeConversationContentPart(property.Value, options); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("part"u8)) { - eventId = property.Value.GetString(); + internalContentPart = ConversationContentPart.DeserializeConversationContentPart(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseContentPartDone( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, contentIndex, - part); + internalContentPart); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel } } - InternalRealtimeServerEventResponseContentPartDone IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseContentPartDone IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseContentPartDone)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseContentPartDone(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseContentPartDone IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseContentPartDone FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseContentPartDone internalRealtimeServerEventResponseContentPartDone) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseContentPartDone(document.RootElement); + if (internalRealtimeServerEventResponseContentPartDone == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseContentPartDone, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseContentPartDone(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseContentPartDone(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.cs b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.cs index 72e744062..d54ce3321 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseContentPartDone.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseContentPartDone : ConversationUpdate { - internal InternalRealtimeServerEventResponseContentPartDone(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId) + internal InternalRealtimeServerEventResponseContentPartDone(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemContentPartFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(internalContentPart, nameof(internalContentPart)); - - Kind = ConversationUpdateKind.ItemContentPartFinished; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal InternalRealtimeServerEventResponseContentPartDone(string eventId, stri _internalContentPart = internalContentPart; } - internal InternalRealtimeServerEventResponseContentPartDone(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseContentPartDone(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, ConversationContentPart internalContentPart) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,13 +27,12 @@ internal InternalRealtimeServerEventResponseContentPartDone(ConversationUpdateKi _internalContentPart = internalContentPart; } - internal InternalRealtimeServerEventResponseContentPartDone() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.Serialization.cs index 195b48e29..987eff1d5 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseFunctionCallArgumentsDelta : IJsonModel { + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseFunctionCallArgumentsDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteStringValue(Delta); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseFunctionCallArgumentsDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseFunctionCallArgumentsDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseFunctionCallArgumentsDelta)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseFunctionCallArgumentsDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDelta DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDelta DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; string callId = default; string delta = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("item_id"u8)) { - callId = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("output_index"u8)) { - delta = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("call_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("delta"u8)) { - eventId = property.Value.GetString(); + delta = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseFunctionCallArgumentsDelta( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDelta De delta); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseFunctionCallArgumentsDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseFunctionCallArgumentsDelta)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseFunctionCallArgumentsDelta IPersistableModel< string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseFunctionCallArgumentsDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseFunctionCallArgumentsDelta internalRealtimeServerEventResponseFunctionCallArgumentsDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(document.RootElement); + if (internalRealtimeServerEventResponseFunctionCallArgumentsDelta == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseFunctionCallArgumentsDelta, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.cs b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.cs index 1f5315514..8e3b5317c 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDelta.cs @@ -9,15 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseFunctionCallArgumentsDelta : ConversationUpdate { - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(string eventId, string responseId, string itemId, int outputIndex, string callId, string delta) : base(eventId) + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(string eventId, string responseId, string itemId, int outputIndex, string callId, string delta) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingFunctionCallArgumentsDelta) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(callId, nameof(callId)); - Argument.AssertNotNull(delta, nameof(delta)); - - Kind = ConversationUpdateKind.ItemStreamingFunctionCallArgumentsDelta; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -25,7 +18,7 @@ internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(string ev Delta = delta; } - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, string callId, string delta) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, string callId, string delta) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -34,14 +27,14 @@ internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta(Conversat Delta = delta; } - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDelta() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public string CallId { get; } + public string Delta { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.Serialization.cs index e38140d23..1e772c69c 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseFunctionCallArgumentsDone : IJsonModel { + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseFunctionCallArgumentsDone)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("call_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("call_id") != true) { writer.WritePropertyName("call_id"u8); writer.WriteStringValue(CallId); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseFunctionCallArgumentsDone IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseFunctionCallArgumentsDone IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseFunctionCallArgumentsDone)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseFunctionCallArgumentsDone)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDone DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDone DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; string callId = default; string arguments = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("call_id"u8)) + if (prop.NameEquals("item_id"u8)) { - callId = property.Value.GetString(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("output_index"u8)) { - arguments = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("call_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + callId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("arguments"u8)) { - eventId = property.Value.GetString(); + arguments = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseFunctionCallArgumentsDone( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static InternalRealtimeServerEventResponseFunctionCallArgumentsDone Des arguments); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseFunctionCallArgumentsDone IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseFunctionCallArgumentsDone)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseFunctionCallArgumentsDone IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseFunctionCallArgumentsDone FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseFunctionCallArgumentsDone internalRealtimeServerEventResponseFunctionCallArgumentsDone) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(document.RootElement); + if (internalRealtimeServerEventResponseFunctionCallArgumentsDone == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseFunctionCallArgumentsDone, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseFunctionCallArgumentsDone(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseFunctionCallArgumentsDone(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.cs b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.cs index 36ab2bbf4..4570d31ab 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseFunctionCallArgumentsDone.cs @@ -9,15 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseFunctionCallArgumentsDone : ConversationUpdate { - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(string eventId, string responseId, string itemId, int outputIndex, string callId, string arguments) : base(eventId) + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(string eventId, string responseId, string itemId, int outputIndex, string callId, string arguments) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingFunctionCallArgumentsFinished) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(callId, nameof(callId)); - Argument.AssertNotNull(arguments, nameof(arguments)); - - Kind = ConversationUpdateKind.ItemStreamingFunctionCallArgumentsFinished; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -25,7 +18,7 @@ internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(string eve Arguments = arguments; } - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, string callId, string arguments) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, string callId, string arguments) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -34,14 +27,14 @@ internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone(Conversati Arguments = arguments; } - internal InternalRealtimeServerEventResponseFunctionCallArgumentsDone() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public string CallId { get; } + public string Arguments { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.Serialization.cs b/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.Serialization.cs index f0a88bb66..663b7a5e9 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.Serialization.cs @@ -7,154 +7,131 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseTextDelta : IJsonModel { + internal InternalRealtimeServerEventResponseTextDelta() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerEventResponseTextDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("response_id") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("response_id") != true) { writer.WritePropertyName("response_id"u8); writer.WriteStringValue(ResponseId); } - if (SerializedAdditionalRawData?.ContainsKey("item_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("item_id") != true) { writer.WritePropertyName("item_id"u8); writer.WriteStringValue(ItemId); } - if (SerializedAdditionalRawData?.ContainsKey("output_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output_index") != true) { writer.WritePropertyName("output_index"u8); writer.WriteNumberValue(OutputIndex); } - if (SerializedAdditionalRawData?.ContainsKey("content_index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("content_index") != true) { writer.WritePropertyName("content_index"u8); writer.WriteNumberValue(ContentIndex); } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteStringValue(Delta); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeServerEventResponseTextDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerEventResponseTextDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseTextDelta)JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerEventResponseTextDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerEventResponseTextDelta(document.RootElement, options); } - internal static InternalRealtimeServerEventResponseTextDelta DeserializeInternalRealtimeServerEventResponseTextDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerEventResponseTextDelta DeserializeInternalRealtimeServerEventResponseTextDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string eventId = default; + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); string responseId = default; string itemId = default; int outputIndex = default; int contentIndex = default; string delta = default; - ConversationUpdateKind type = default; - string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("response_id"u8)) + if (prop.NameEquals("event_id"u8)) { - responseId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("item_id"u8)) + if (prop.NameEquals("type"u8)) { - itemId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } - if (property.NameEquals("output_index"u8)) + if (prop.NameEquals("response_id"u8)) { - outputIndex = property.Value.GetInt32(); + responseId = prop.Value.GetString(); continue; } - if (property.NameEquals("content_index"u8)) + if (prop.NameEquals("item_id"u8)) { - contentIndex = property.Value.GetInt32(); + itemId = prop.Value.GetString(); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("output_index"u8)) { - delta = property.Value.GetString(); + outputIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("content_index"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + contentIndex = prop.Value.GetInt32(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("delta"u8)) { - eventId = property.Value.GetString(); + delta = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalRealtimeServerEventResponseTextDelta( - type, eventId, - serializedAdditionalRawData, + kind, + additionalBinaryDataProperties, responseId, itemId, outputIndex, @@ -162,10 +139,11 @@ internal static InternalRealtimeServerEventResponseTextDelta DeserializeInternal delta); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -175,15 +153,16 @@ BinaryData IPersistableModel.Write } } - InternalRealtimeServerEventResponseTextDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerEventResponseTextDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerEventResponseTextDelta)PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerEventResponseTextDelta(document.RootElement, options); } default: @@ -193,15 +172,20 @@ InternalRealtimeServerEventResponseTextDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerEventResponseTextDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerEventResponseTextDelta internalRealtimeServerEventResponseTextDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerEventResponseTextDelta(document.RootElement); + if (internalRealtimeServerEventResponseTextDelta == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerEventResponseTextDelta, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerEventResponseTextDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerEventResponseTextDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.cs b/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.cs index 64ec3101f..533d2ac3c 100644 --- a/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.cs +++ b/src/Generated/Models/InternalRealtimeServerEventResponseTextDelta.cs @@ -9,14 +9,8 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerEventResponseTextDelta : ConversationUpdate { - internal InternalRealtimeServerEventResponseTextDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId) + internal InternalRealtimeServerEventResponseTextDelta(string eventId, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId, RealtimeConversation.ConversationUpdateKind.ItemStreamingPartTextDelta) { - Argument.AssertNotNull(eventId, nameof(eventId)); - Argument.AssertNotNull(responseId, nameof(responseId)); - Argument.AssertNotNull(itemId, nameof(itemId)); - Argument.AssertNotNull(delta, nameof(delta)); - - Kind = ConversationUpdateKind.ItemStreamingPartTextDelta; ResponseId = responseId; ItemId = itemId; OutputIndex = outputIndex; @@ -24,7 +18,7 @@ internal InternalRealtimeServerEventResponseTextDelta(string eventId, string res Delta = delta; } - internal InternalRealtimeServerEventResponseTextDelta(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(kind, eventId, serializedAdditionalRawData) + internal InternalRealtimeServerEventResponseTextDelta(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties, string responseId, string itemId, int outputIndex, int contentIndex, string delta) : base(eventId, kind, additionalBinaryDataProperties) { ResponseId = responseId; ItemId = itemId; @@ -33,14 +27,14 @@ internal InternalRealtimeServerEventResponseTextDelta(ConversationUpdateKind kin Delta = delta; } - internal InternalRealtimeServerEventResponseTextDelta() - { - } - public string ResponseId { get; } + public string ItemId { get; } + public int OutputIndex { get; } + public int ContentIndex { get; } + public string Delta { get; } } } diff --git a/src/Generated/Models/InternalRealtimeServerVadTurnDetection.Serialization.cs b/src/Generated/Models/InternalRealtimeServerVadTurnDetection.Serialization.cs index d5daf900e..6bc541de0 100644 --- a/src/Generated/Models/InternalRealtimeServerVadTurnDetection.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeServerVadTurnDetection.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { @@ -14,121 +15,99 @@ internal partial class InternalRealtimeServerVadTurnDetection : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeServerVadTurnDetection)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("threshold") != true && Optional.IsDefined(Threshold)) + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Threshold) && _additionalBinaryDataProperties?.ContainsKey("threshold") != true) { writer.WritePropertyName("threshold"u8); writer.WriteNumberValue(Threshold.Value); } - if (SerializedAdditionalRawData?.ContainsKey("prefix_padding_ms") != true && Optional.IsDefined(PrefixPaddingMs)) + if (Optional.IsDefined(PrefixPaddingMs) && _additionalBinaryDataProperties?.ContainsKey("prefix_padding_ms") != true) { writer.WritePropertyName("prefix_padding_ms"u8); - SerializePrefixPaddingMs(writer, options); + this.SerializePrefixPaddingMs(writer, options); } - if (SerializedAdditionalRawData?.ContainsKey("silence_duration_ms") != true && Optional.IsDefined(SilenceDurationMs)) + if (Optional.IsDefined(SilenceDurationMs) && _additionalBinaryDataProperties?.ContainsKey("silence_duration_ms") != true) { writer.WritePropertyName("silence_duration_ms"u8); - SerializeSilenceDurationMs(writer, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } + this.SerializeSilenceDurationMs(writer, options); } - writer.WriteEndObject(); } - InternalRealtimeServerVadTurnDetection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeServerVadTurnDetection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeServerVadTurnDetection)JsonModelCreateCore(ref reader, options); + + protected override ConversationTurnDetectionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeServerVadTurnDetection)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeServerVadTurnDetection(document.RootElement, options); } - internal static InternalRealtimeServerVadTurnDetection DeserializeInternalRealtimeServerVadTurnDetection(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeServerVadTurnDetection DeserializeInternalRealtimeServerVadTurnDetection(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + RealtimeConversation.ConversationTurnDetectionKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); float? threshold = default; TimeSpan? prefixPaddingMs = default; TimeSpan? silenceDurationMs = default; - ConversationTurnDetectionKind type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("threshold"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - threshold = property.Value.GetSingle(); + kind = prop.Value.GetString().ToConversationTurnDetectionKind(); continue; } - if (property.NameEquals("prefix_padding_ms"u8)) + if (prop.NameEquals("threshold"u8)) { - DeserializeMillisecondDuration(property, ref prefixPaddingMs); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + threshold = prop.Value.GetSingle(); continue; } - if (property.NameEquals("silence_duration_ms"u8)) + if (prop.NameEquals("prefix_padding_ms"u8)) { - DeserializeMillisecondDuration(property, ref silenceDurationMs); + DeserializeMillisecondDuration(prop, ref prefixPaddingMs); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("silence_duration_ms"u8)) { - type = property.Value.GetString().ToConversationTurnDetectionKind(); + DeserializeMillisecondDuration(prop, ref silenceDurationMs); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeServerVadTurnDetection(type, serializedAdditionalRawData, threshold, prefixPaddingMs, silenceDurationMs); + return new InternalRealtimeServerVadTurnDetection(kind, additionalBinaryDataProperties, threshold, prefixPaddingMs, silenceDurationMs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -138,15 +117,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalRealtimeServerVadTurnDetection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeServerVadTurnDetection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeServerVadTurnDetection)PersistableModelCreateCore(data, options); + protected override ConversationTurnDetectionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeServerVadTurnDetection(document.RootElement, options); } default: @@ -156,15 +136,20 @@ InternalRealtimeServerVadTurnDetection IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeServerVadTurnDetection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeServerVadTurnDetection internalRealtimeServerVadTurnDetection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeServerVadTurnDetection(document.RootElement); + if (internalRealtimeServerVadTurnDetection == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeServerVadTurnDetection, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeServerVadTurnDetection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeServerVadTurnDetection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeServerVadTurnDetection.cs b/src/Generated/Models/InternalRealtimeServerVadTurnDetection.cs index e0ec40082..2d781bf81 100644 --- a/src/Generated/Models/InternalRealtimeServerVadTurnDetection.cs +++ b/src/Generated/Models/InternalRealtimeServerVadTurnDetection.cs @@ -9,12 +9,11 @@ namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeServerVadTurnDetection : ConversationTurnDetectionOptions { - public InternalRealtimeServerVadTurnDetection() + public InternalRealtimeServerVadTurnDetection() : base(RealtimeConversation.ConversationTurnDetectionKind.ServerVoiceActivityDetection) { - Kind = ConversationTurnDetectionKind.ServerVoiceActivityDetection; } - internal InternalRealtimeServerVadTurnDetection(ConversationTurnDetectionKind kind, IDictionary serializedAdditionalRawData, float? threshold, TimeSpan? prefixPaddingMs, TimeSpan? silenceDurationMs) : base(kind, serializedAdditionalRawData) + internal InternalRealtimeServerVadTurnDetection(RealtimeConversation.ConversationTurnDetectionKind kind, IDictionary additionalBinaryDataProperties, float? threshold, TimeSpan? prefixPaddingMs, TimeSpan? silenceDurationMs) : base(kind, additionalBinaryDataProperties) { Threshold = threshold; PrefixPaddingMs = prefixPaddingMs; @@ -22,7 +21,9 @@ internal InternalRealtimeServerVadTurnDetection(ConversationTurnDetectionKind ki } public float? Threshold { get; set; } + public TimeSpan? PrefixPaddingMs { get; set; } + public TimeSpan? SilenceDurationMs { get; set; } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.Serialization.cs b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.Serialization.cs index 0186db465..ae7ba45e0 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeToolChoiceFunctionObject : IJsonModel { + internal InternalRealtimeToolChoiceFunctionObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeToolChoiceFunctionObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRealtimeToolChoiceFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeToolChoiceFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRealtimeToolChoiceFunctionObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeToolChoiceObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeToolChoiceFunctionObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeToolChoiceFunctionObject(document.RootElement, options); } - internal static InternalRealtimeToolChoiceFunctionObject DeserializeInternalRealtimeToolChoiceFunctionObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeToolChoiceFunctionObject DeserializeInternalRealtimeToolChoiceFunctionObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + ConversationToolKind @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalRealtimeToolChoiceFunctionObjectFunction function = default; - ConversationToolKind type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("function"u8)) + if (prop.NameEquals("type"u8)) { - function = InternalRealtimeToolChoiceFunctionObjectFunction.DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(property.Value, options); + @type = new ConversationToolKind(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("function"u8)) { - type = new ConversationToolKind(property.Value.GetString()); + function = InternalRealtimeToolChoiceFunctionObjectFunction.DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeToolChoiceFunctionObject(type, serializedAdditionalRawData, function); + return new InternalRealtimeToolChoiceFunctionObject(@type, additionalBinaryDataProperties, function); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalRealtimeToolChoiceFunctionObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeToolChoiceFunctionObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRealtimeToolChoiceFunctionObject)PersistableModelCreateCore(data, options); + protected override InternalRealtimeToolChoiceObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeToolChoiceFunctionObject(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalRealtimeToolChoiceFunctionObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRealtimeToolChoiceFunctionObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeToolChoiceFunctionObject internalRealtimeToolChoiceFunctionObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeToolChoiceFunctionObject(document.RootElement); + if (internalRealtimeToolChoiceFunctionObject == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeToolChoiceFunctionObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeToolChoiceFunctionObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeToolChoiceFunctionObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.cs b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.cs index f072dc3a8..e5a4267e6 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObject.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeToolChoiceFunctionObject : InternalRealtimeToolChoiceObject { - public InternalRealtimeToolChoiceFunctionObject(InternalRealtimeToolChoiceFunctionObjectFunction function) + public InternalRealtimeToolChoiceFunctionObject(InternalRealtimeToolChoiceFunctionObjectFunction function) : base(ConversationToolKind.Function) { Argument.AssertNotNull(function, nameof(function)); - Type = ConversationToolKind.Function; Function = function; } - internal InternalRealtimeToolChoiceFunctionObject(ConversationToolKind type, IDictionary serializedAdditionalRawData, InternalRealtimeToolChoiceFunctionObjectFunction function) : base(type, serializedAdditionalRawData) + internal InternalRealtimeToolChoiceFunctionObject(ConversationToolKind @type, IDictionary additionalBinaryDataProperties, InternalRealtimeToolChoiceFunctionObjectFunction function) : base(@type, additionalBinaryDataProperties) { Function = function; } - internal InternalRealtimeToolChoiceFunctionObject() - { - } - public InternalRealtimeToolChoiceFunctionObjectFunction Function { get; set; } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.Serialization.cs b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.Serialization.cs index cd8398e92..14cea7729 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeToolChoiceFunctionObjectFunction : IJsonModel { + internal InternalRealtimeToolChoiceFunctionObjectFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeToolChoiceFunctionObjectFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8Json } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8Json #endif } } - writer.WriteEndObject(); } - InternalRealtimeToolChoiceFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeToolChoiceFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeToolChoiceFunctionObjectFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeToolChoiceFunctionObjectFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(document.RootElement, options); } - internal static InternalRealtimeToolChoiceFunctionObjectFunction DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeToolChoiceFunctionObjectFunction DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRealtimeToolChoiceFunctionObjectFunction(name, serializedAdditionalRawData); + return new InternalRealtimeToolChoiceFunctionObjectFunction(name, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.W } } - InternalRealtimeToolChoiceFunctionObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeToolChoiceFunctionObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeToolChoiceFunctionObjectFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalRealtimeToolChoiceFunctionObjectFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeToolChoiceFunctionObjectFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeToolChoiceFunctionObjectFunction internalRealtimeToolChoiceFunctionObjectFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(document.RootElement); + if (internalRealtimeToolChoiceFunctionObjectFunction == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeToolChoiceFunctionObjectFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeToolChoiceFunctionObjectFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeToolChoiceFunctionObjectFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.cs b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.cs index 45162c2bb..c10d15fb6 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceFunctionObjectFunction.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class InternalRealtimeToolChoiceFunctionObjectFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalRealtimeToolChoiceFunctionObjectFunction(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,16 +19,18 @@ public InternalRealtimeToolChoiceFunctionObjectFunction(string name) Name = name; } - internal InternalRealtimeToolChoiceFunctionObjectFunction(string name, IDictionary serializedAdditionalRawData) + internal InternalRealtimeToolChoiceFunctionObjectFunction(string name, IDictionary additionalBinaryDataProperties) { Name = name; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalRealtimeToolChoiceFunctionObjectFunction() + public string Name { get; set; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Name { get; set; } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceObject.Serialization.cs b/src/Generated/Models/InternalRealtimeToolChoiceObject.Serialization.cs index c7cd2c8df..a35cb1d2a 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceObject.Serialization.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceObject.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { [PersistableModelProxy(typeof(UnknownRealtimeToolChoiceObject))] - internal partial class InternalRealtimeToolChoiceObject : IJsonModel + internal abstract partial class InternalRealtimeToolChoiceObject : IJsonModel { + internal InternalRealtimeToolChoiceObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeToolChoiceObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,43 +55,43 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalRealtimeToolChoiceObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeToolChoiceObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRealtimeToolChoiceObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeToolChoiceObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeToolChoiceObject(document.RootElement, options); } - internal static InternalRealtimeToolChoiceObject DeserializeInternalRealtimeToolChoiceObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRealtimeToolChoiceObject DeserializeInternalRealtimeToolChoiceObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "function": return InternalRealtimeToolChoiceFunctionObject.DeserializeInternalRealtimeToolChoiceFunctionObject(element, options); + case "function": + return InternalRealtimeToolChoiceFunctionObject.DeserializeInternalRealtimeToolChoiceFunctionObject(element, options); } } return UnknownRealtimeToolChoiceObject.DeserializeUnknownRealtimeToolChoiceObject(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -91,15 +101,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalRealtimeToolChoiceObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeToolChoiceObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRealtimeToolChoiceObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeToolChoiceObject(document.RootElement, options); } default: @@ -109,15 +120,20 @@ InternalRealtimeToolChoiceObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRealtimeToolChoiceObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRealtimeToolChoiceObject internalRealtimeToolChoiceObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRealtimeToolChoiceObject(document.RootElement); + if (internalRealtimeToolChoiceObject == null) + { + return null; + } + return BinaryContent.Create(internalRealtimeToolChoiceObject, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRealtimeToolChoiceObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRealtimeToolChoiceObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRealtimeToolChoiceObject.cs b/src/Generated/Models/InternalRealtimeToolChoiceObject.cs index b219a7b10..d97cd6a75 100644 --- a/src/Generated/Models/InternalRealtimeToolChoiceObject.cs +++ b/src/Generated/Models/InternalRealtimeToolChoiceObject.cs @@ -9,17 +9,25 @@ namespace OpenAI.RealtimeConversation { internal abstract partial class InternalRealtimeToolChoiceObject { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalRealtimeToolChoiceObject() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalRealtimeToolChoiceObject(ConversationToolKind @type) { + Type = @type; } - internal InternalRealtimeToolChoiceObject(ConversationToolKind type, IDictionary serializedAdditionalRawData) + internal InternalRealtimeToolChoiceObject(ConversationToolKind @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal ConversationToolKind Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRequestMessageTextContent.Serialization.cs b/src/Generated/Models/InternalRequestMessageTextContent.Serialization.cs index abecb82df..dbe004b80 100644 --- a/src/Generated/Models/InternalRequestMessageTextContent.Serialization.cs +++ b/src/Generated/Models/InternalRequestMessageTextContent.Serialization.cs @@ -7,61 +7,83 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRequestMessageTextContent : IJsonModel { - InternalRequestMessageTextContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalRequestMessageTextContent() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalRequestMessageTextContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalRequestMessageTextContent)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); } + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(InternalText); + } + } + InternalRequestMessageTextContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRequestMessageTextContent)JsonModelCreateCore(ref reader, options); + + protected override MessageContent 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(InternalRequestMessageTextContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRequestMessageTextContent(document.RootElement, options); } - internal static InternalRequestMessageTextContent DeserializeInternalRequestMessageTextContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRequestMessageTextContent DeserializeInternalRequestMessageTextContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalMessageRequestContentTextObjectType type = default; - string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalMessageRequestContentTextObjectType @type = default; + string internalText = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalMessageRequestContentTextObjectType(property.Value.GetString()); + @type = new InternalMessageRequestContentTextObjectType(prop.Value.GetString()); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = property.Value.GetString(); + internalText = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRequestMessageTextContent(serializedAdditionalRawData, type, text); + return new InternalRequestMessageTextContent(additionalBinaryDataProperties, @type, internalText); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - InternalRequestMessageTextContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRequestMessageTextContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRequestMessageTextContent)PersistableModelCreateCore(data, options); + protected override MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRequestMessageTextContent(document.RootElement, options); } default: @@ -89,15 +112,20 @@ InternalRequestMessageTextContent IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRequestMessageTextContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRequestMessageTextContent internalRequestMessageTextContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRequestMessageTextContent(document.RootElement); + if (internalRequestMessageTextContent == null) + { + return null; + } + return BinaryContent.Create(internalRequestMessageTextContent, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRequestMessageTextContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRequestMessageTextContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRequestMessageTextContent.cs b/src/Generated/Models/InternalRequestMessageTextContent.cs index 7fb763cb2..fc2971d5b 100644 --- a/src/Generated/Models/InternalRequestMessageTextContent.cs +++ b/src/Generated/Models/InternalRequestMessageTextContent.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { @@ -16,16 +17,12 @@ public InternalRequestMessageTextContent(string internalText) InternalText = internalText; } - internal InternalRequestMessageTextContent(IDictionary serializedAdditionalRawData, InternalMessageRequestContentTextObjectType type, string internalText) : base(serializedAdditionalRawData) + internal InternalRequestMessageTextContent(IDictionary additionalBinaryDataProperties, InternalMessageRequestContentTextObjectType @type, string internalText) : base(additionalBinaryDataProperties) { - Type = type; + Type = @type; InternalText = internalText; } - internal InternalRequestMessageTextContent() - { - } - - public InternalMessageRequestContentTextObjectType Type { get; } = InternalMessageRequestContentTextObjectType.Text; + public InternalMessageRequestContentTextObjectType Type { get; } = "text"; } } diff --git a/src/Generated/Models/InternalRequiredFunctionToolCall.Serialization.cs b/src/Generated/Models/InternalRequiredFunctionToolCall.Serialization.cs index ab8bbc81c..b0d1cbb0b 100644 --- a/src/Generated/Models/InternalRequiredFunctionToolCall.Serialization.cs +++ b/src/Generated/Models/InternalRequiredFunctionToolCall.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRequiredFunctionToolCall : IJsonModel { + internal InternalRequiredFunctionToolCall() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRequiredFunctionToolCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteObjectValue(_type, options); } - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(_internalFunction, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, M } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, M #endif } } - writer.WriteEndObject(); } - InternalRequiredFunctionToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRequiredFunctionToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRequiredFunctionToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRequiredFunctionToolCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRequiredFunctionToolCall(document.RootElement, options); } - internal static InternalRequiredFunctionToolCall DeserializeInternalRequiredFunctionToolCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRequiredFunctionToolCall DeserializeInternalRequiredFunctionToolCall(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - object type = default; - InternalRunToolCallObjectFunction function = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + object @type = default; + InternalRunToolCallObjectFunction internalFunction = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetObject(); + @type = prop.Value.GetObject(); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("function"u8)) { - function = InternalRunToolCallObjectFunction.DeserializeInternalRunToolCallObjectFunction(property.Value, options); + internalFunction = InternalRunToolCallObjectFunction.DeserializeInternalRunToolCallObjectFunction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRequiredFunctionToolCall(id, type, function, serializedAdditionalRawData); + return new InternalRequiredFunctionToolCall(id, @type, internalFunction, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalRequiredFunctionToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRequiredFunctionToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRequiredFunctionToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRequiredFunctionToolCall(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalRequiredFunctionToolCall IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRequiredFunctionToolCall FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRequiredFunctionToolCall internalRequiredFunctionToolCall) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRequiredFunctionToolCall(document.RootElement); + if (internalRequiredFunctionToolCall == null) + { + return null; + } + return BinaryContent.Create(internalRequiredFunctionToolCall, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRequiredFunctionToolCall(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRequiredFunctionToolCall(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRequiredFunctionToolCall.cs b/src/Generated/Models/InternalRequiredFunctionToolCall.cs index 3d44b809d..6df47de6d 100644 --- a/src/Generated/Models/InternalRequiredFunctionToolCall.cs +++ b/src/Generated/Models/InternalRequiredFunctionToolCall.cs @@ -9,28 +9,28 @@ namespace OpenAI.Assistants { internal partial class InternalRequiredFunctionToolCall { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRequiredFunctionToolCall(string id, InternalRunToolCallObjectFunction internalFunction) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(internalFunction, nameof(internalFunction)); - Id = id; _internalFunction = internalFunction; } - internal InternalRequiredFunctionToolCall(string id, object type, InternalRunToolCallObjectFunction internalFunction, IDictionary serializedAdditionalRawData) + internal InternalRequiredFunctionToolCall(string id, object @type, InternalRunToolCallObjectFunction internalFunction, IDictionary additionalBinaryDataProperties) { Id = id; - _type = type; + _type = @type; _internalFunction = internalFunction; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalRequiredFunctionToolCall() + public string Id { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string Id { get; } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs b/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs index 66e2b97f1..42443b789 100644 --- a/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs +++ b/src/Generated/Models/InternalResponseFormatJsonObject.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { @@ -14,84 +15,62 @@ internal partial class InternalResponseFormatJsonObject : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalResponseFormatJsonObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalResponseFormatJsonObject)JsonModelCreateCore(ref reader, options); + + protected override InternalOmniTypedResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalResponseFormatJsonObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseFormatJsonObject(document.RootElement, options); } - internal static InternalResponseFormatJsonObject DeserializeInternalResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseFormatJsonObject DeserializeInternalResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "json_object"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalResponseFormatJsonObject(type, serializedAdditionalRawData); + return new InternalResponseFormatJsonObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalResponseFormatJsonObject)PersistableModelCreateCore(data, options); + protected override InternalOmniTypedResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseFormatJsonObject(document.RootElement, options); } default: @@ -119,15 +99,20 @@ InternalResponseFormatJsonObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalResponseFormatJsonObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseFormatJsonObject internalResponseFormatJsonObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseFormatJsonObject(document.RootElement); + if (internalResponseFormatJsonObject == null) + { + return null; + } + return BinaryContent.Create(internalResponseFormatJsonObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalResponseFormatJsonObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonObject.cs b/src/Generated/Models/InternalResponseFormatJsonObject.cs index b62b1891f..d6348da4a 100644 --- a/src/Generated/Models/InternalResponseFormatJsonObject.cs +++ b/src/Generated/Models/InternalResponseFormatJsonObject.cs @@ -9,12 +9,11 @@ namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonObject : InternalOmniTypedResponseFormat { - public InternalResponseFormatJsonObject() + public InternalResponseFormatJsonObject() : base("json_object") { - Type = "json_object"; } - internal InternalResponseFormatJsonObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalResponseFormatJsonObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs b/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs index 1746508f2..67876ee47 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchema.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonSchema : IJsonModel { + internal InternalResponseFormatJsonSchema() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalResponseFormatJsonSchema)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("json_schema") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("json_schema") != true) { writer.WritePropertyName("json_schema"u8); writer.WriteObjectValue(JsonSchema, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalResponseFormatJsonSchema)JsonModelCreateCore(ref reader, options); + + protected override InternalOmniTypedResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchema)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseFormatJsonSchema(document.RootElement, options); } - internal static InternalResponseFormatJsonSchema DeserializeInternalResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseFormatJsonSchema DeserializeInternalResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "json_schema"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalResponseFormatJsonSchemaJsonSchema jsonSchema = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("json_schema"u8)) + if (prop.NameEquals("type"u8)) { - jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("json_schema"u8)) { - type = property.Value.GetString(); + jsonSchema = InternalResponseFormatJsonSchemaJsonSchema.DeserializeInternalResponseFormatJsonSchemaJsonSchema(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + return new InternalResponseFormatJsonSchema(@type, additionalBinaryDataProperties, jsonSchema); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalResponseFormatJsonSchema)PersistableModelCreateCore(data, options); + protected override InternalOmniTypedResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseFormatJsonSchema(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalResponseFormatJsonSchema IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalResponseFormatJsonSchema FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseFormatJsonSchema internalResponseFormatJsonSchema) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseFormatJsonSchema(document.RootElement); + if (internalResponseFormatJsonSchema == null) + { + return null; + } + return BinaryContent.Create(internalResponseFormatJsonSchema, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalResponseFormatJsonSchema(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchema(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchema.cs b/src/Generated/Models/InternalResponseFormatJsonSchema.cs index 739eb22b9..91aa9e238 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchema.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchema.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonSchema : InternalOmniTypedResponseFormat { - public InternalResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) + public InternalResponseFormatJsonSchema(InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base("json_schema") { Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); - Type = "json_schema"; JsonSchema = jsonSchema; } - internal InternalResponseFormatJsonSchema(string type, IDictionary serializedAdditionalRawData, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + internal InternalResponseFormatJsonSchema(string @type, IDictionary additionalBinaryDataProperties, InternalResponseFormatJsonSchemaJsonSchema jsonSchema) : base(@type, additionalBinaryDataProperties) { JsonSchema = jsonSchema; } - internal InternalResponseFormatJsonSchema() - { - } - public InternalResponseFormatJsonSchemaJsonSchema JsonSchema { get; set; } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs b/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs index 5b9c4d930..39166704f 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.Serialization.cs @@ -7,43 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonSchemaJsonSchema : IJsonModel { + internal InternalResponseFormatJsonSchemaJsonSchema() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalResponseFormatJsonSchemaJsonSchema)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("description") != true && Optional.IsDefined(Description)) + if (Optional.IsDefined(Description) && _additionalBinaryDataProperties?.ContainsKey("description") != true) { writer.WritePropertyName("description"u8); writer.WriteStringValue(Description); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("schema") != true && Optional.IsDefined(Schema)) - { - writer.WritePropertyName("schema"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Schema); -#else - using (JsonDocument document = JsonDocument.Parse(Schema)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (SerializedAdditionalRawData?.ContainsKey("strict") != true && Optional.IsDefined(Strict)) + if (Optional.IsDefined(Strict) && _additionalBinaryDataProperties?.ContainsKey("strict") != true) { if (Strict != null) { @@ -52,12 +50,24 @@ void IJsonModel.Write(Utf8JsonWriter } else { - writer.WriteNull("strict"); + writer.WriteNull("strict"u8); } } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(Schema) && _additionalBinaryDataProperties?.ContainsKey("schema") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("schema"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Schema); +#else + using (JsonDocument document = JsonDocument.Parse(Schema)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +75,7 @@ void IJsonModel.Write(Utf8JsonWriter } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,80 +84,76 @@ void IJsonModel.Write(Utf8JsonWriter #endif } } - writer.WriteEndObject(); } - InternalResponseFormatJsonSchemaJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalResponseFormatJsonSchemaJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalResponseFormatJsonSchemaJsonSchema JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaJsonSchema)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement, options); } - internal static InternalResponseFormatJsonSchemaJsonSchema DeserializeInternalResponseFormatJsonSchemaJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseFormatJsonSchemaJsonSchema DeserializeInternalResponseFormatJsonSchemaJsonSchema(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string description = default; string name = default; - BinaryData schema = default; bool? strict = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + BinaryData schema = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("description"u8)) + if (prop.NameEquals("description"u8)) { - description = property.Value.GetString(); + description = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("schema"u8)) + if (prop.NameEquals("strict"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + strict = null; continue; } - schema = BinaryData.FromString(property.Value.GetRawText()); + strict = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("strict"u8)) + if (prop.NameEquals("schema"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - strict = null; continue; } - strict = property.Value.GetBoolean(); + schema = BinaryData.FromString(prop.Value.GetRawText()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalResponseFormatJsonSchemaJsonSchema(description, name, schema, strict, serializedAdditionalRawData); + return new InternalResponseFormatJsonSchemaJsonSchema(description, name, strict, schema, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -157,15 +163,16 @@ BinaryData IPersistableModel.Write(M } } - InternalResponseFormatJsonSchemaJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseFormatJsonSchemaJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalResponseFormatJsonSchemaJsonSchema 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement, options); } default: @@ -175,15 +182,20 @@ InternalResponseFormatJsonSchemaJsonSchema IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalResponseFormatJsonSchemaJsonSchema FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseFormatJsonSchemaJsonSchema internalResponseFormatJsonSchemaJsonSchema) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement); + if (internalResponseFormatJsonSchemaJsonSchema == null) + { + return null; + } + return BinaryContent.Create(internalResponseFormatJsonSchemaJsonSchema, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalResponseFormatJsonSchemaJsonSchema(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchemaJsonSchema(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs b/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs index 533d36db0..8fe22b88a 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchemaJsonSchema.cs @@ -4,12 +4,14 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonSchemaJsonSchema { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalResponseFormatJsonSchemaJsonSchema(string name) { Argument.AssertNotNull(name, nameof(name)); @@ -17,21 +19,25 @@ public InternalResponseFormatJsonSchemaJsonSchema(string name) Name = name; } - internal InternalResponseFormatJsonSchemaJsonSchema(string description, string name, BinaryData schema, bool? strict, IDictionary serializedAdditionalRawData) + internal InternalResponseFormatJsonSchemaJsonSchema(string description, string name, bool? strict, BinaryData schema, IDictionary additionalBinaryDataProperties) { Description = description; Name = name; - Schema = schema; Strict = strict; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalResponseFormatJsonSchemaJsonSchema() - { + Schema = schema; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Description { get; set; } + public string Name { get; set; } + public bool? Strict { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs b/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs index d77918543..7954fe60a 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { @@ -14,18 +15,23 @@ internal partial class InternalResponseFormatJsonSchemaSchema : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalResponseFormatJsonSchemaSchema)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); foreach (var item in AdditionalProperties) { writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -33,43 +39,40 @@ void IJsonModel.Write(Utf8JsonWriter wri } #endif } - writer.WriteEndObject(); } - InternalResponseFormatJsonSchemaSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalResponseFormatJsonSchemaSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalResponseFormatJsonSchemaSchema JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalResponseFormatJsonSchemaSchema)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement, options); } - internal static InternalResponseFormatJsonSchemaSchema DeserializeInternalResponseFormatJsonSchemaSchema(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseFormatJsonSchemaSchema DeserializeInternalResponseFormatJsonSchemaSchema(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } - additionalProperties = additionalPropertiesDictionary; return new InternalResponseFormatJsonSchemaSchema(additionalProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -79,15 +82,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalResponseFormatJsonSchemaSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseFormatJsonSchemaSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalResponseFormatJsonSchemaSchema 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement, options); } default: @@ -97,15 +101,20 @@ InternalResponseFormatJsonSchemaSchema IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalResponseFormatJsonSchemaSchema FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseFormatJsonSchemaSchema internalResponseFormatJsonSchemaSchema) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement); + if (internalResponseFormatJsonSchemaSchema == null) + { + return null; + } + return BinaryContent.Create(internalResponseFormatJsonSchemaSchema, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalResponseFormatJsonSchemaSchema(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatJsonSchemaSchema(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs b/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs index d00500adb..bd7575c36 100644 --- a/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs +++ b/src/Generated/Models/InternalResponseFormatJsonSchemaSchema.cs @@ -4,21 +4,30 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalResponseFormatJsonSchemaSchema { + private protected IDictionary _additionalBinaryDataProperties; + public InternalResponseFormatJsonSchemaSchema() { - AdditionalProperties = new ChangeTrackingDictionary(); + _additionalBinaryDataProperties = new ChangeTrackingDictionary(); } internal InternalResponseFormatJsonSchemaSchema(IDictionary additionalProperties) { - AdditionalProperties = additionalProperties; + _additionalBinaryDataProperties = additionalProperties; } - public IDictionary AdditionalProperties { get; } + public IDictionary AdditionalProperties => _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalResponseFormatText.Serialization.cs b/src/Generated/Models/InternalResponseFormatText.Serialization.cs index b213da2e7..054bff834 100644 --- a/src/Generated/Models/InternalResponseFormatText.Serialization.cs +++ b/src/Generated/Models/InternalResponseFormatText.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { @@ -14,84 +15,62 @@ internal partial class InternalResponseFormatText : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalResponseFormatText)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalResponseFormatText)JsonModelCreateCore(ref reader, options); + + protected override InternalOmniTypedResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalResponseFormatText)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseFormatText(document.RootElement, options); } - internal static InternalResponseFormatText DeserializeInternalResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseFormatText DeserializeInternalResponseFormatText(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "text"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalResponseFormatText(type, serializedAdditionalRawData); + return new InternalResponseFormatText(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - InternalResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalResponseFormatText)PersistableModelCreateCore(data, options); + protected override InternalOmniTypedResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseFormatText(document.RootElement, options); } default: @@ -119,15 +99,20 @@ InternalResponseFormatText IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalResponseFormatText FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseFormatText internalResponseFormatText) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseFormatText(document.RootElement); + if (internalResponseFormatText == null) + { + return null; + } + return BinaryContent.Create(internalResponseFormatText, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalResponseFormatText(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseFormatText(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseFormatText.cs b/src/Generated/Models/InternalResponseFormatText.cs index efe4d6fce..81ccbc8d1 100644 --- a/src/Generated/Models/InternalResponseFormatText.cs +++ b/src/Generated/Models/InternalResponseFormatText.cs @@ -9,12 +9,11 @@ namespace OpenAI.Internal { internal partial class InternalResponseFormatText : InternalOmniTypedResponseFormat { - public InternalResponseFormatText() + public InternalResponseFormatText() : base("text") { - Type = "text"; } - internal InternalResponseFormatText(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalResponseFormatText(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalResponseMessageTextContent.Serialization.cs b/src/Generated/Models/InternalResponseMessageTextContent.Serialization.cs index 4a89d0389..8272d8d6b 100644 --- a/src/Generated/Models/InternalResponseMessageTextContent.Serialization.cs +++ b/src/Generated/Models/InternalResponseMessageTextContent.Serialization.cs @@ -7,61 +7,83 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalResponseMessageTextContent : IJsonModel { - InternalResponseMessageTextContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalResponseMessageTextContent() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(InternalResponseMessageTextContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalResponseMessageTextContent)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type); } + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) + { + writer.WritePropertyName("text"u8); + writer.WriteObjectValue(_text, options); + } + } + InternalResponseMessageTextContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalResponseMessageTextContent)JsonModelCreateCore(ref reader, options); + + protected override MessageContent 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(InternalResponseMessageTextContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalResponseMessageTextContent(document.RootElement, options); } - internal static InternalResponseMessageTextContent DeserializeInternalResponseMessageTextContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalResponseMessageTextContent DeserializeInternalResponseMessageTextContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string @type = default; InternalMessageContentTextObjectText text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("text"u8)) { - text = InternalMessageContentTextObjectText.DeserializeInternalMessageContentTextObjectText(property.Value, options); + text = InternalMessageContentTextObjectText.DeserializeInternalMessageContentTextObjectText(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalResponseMessageTextContent(serializedAdditionalRawData, type, text); + return new InternalResponseMessageTextContent(additionalBinaryDataProperties, @type, text); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -71,15 +93,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - InternalResponseMessageTextContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalResponseMessageTextContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalResponseMessageTextContent)PersistableModelCreateCore(data, options); + protected override MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalResponseMessageTextContent(document.RootElement, options); } default: @@ -89,15 +112,20 @@ InternalResponseMessageTextContent IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalResponseMessageTextContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalResponseMessageTextContent internalResponseMessageTextContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalResponseMessageTextContent(document.RootElement); + if (internalResponseMessageTextContent == null) + { + return null; + } + return BinaryContent.Create(internalResponseMessageTextContent, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalResponseMessageTextContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalResponseMessageTextContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalResponseMessageTextContent.cs b/src/Generated/Models/InternalResponseMessageTextContent.cs index 83930eb9b..98a3edb86 100644 --- a/src/Generated/Models/InternalResponseMessageTextContent.cs +++ b/src/Generated/Models/InternalResponseMessageTextContent.cs @@ -9,14 +9,10 @@ namespace OpenAI.Assistants { internal partial class InternalResponseMessageTextContent : MessageContent { - internal InternalResponseMessageTextContent(IDictionary serializedAdditionalRawData, string type, InternalMessageContentTextObjectText text) : base(serializedAdditionalRawData) + internal InternalResponseMessageTextContent(IDictionary additionalBinaryDataProperties, string @type, InternalMessageContentTextObjectText text) : base(additionalBinaryDataProperties) { - _type = type; + _type = @type; _text = text; } - - internal InternalResponseMessageTextContent() - { - } } } diff --git a/src/Generated/Models/InternalRunObjectObject.cs b/src/Generated/Models/InternalRunObjectObject.cs index 4f2c77d99..f4488c922 100644 --- a/src/Generated/Models/InternalRunObjectObject.cs +++ b/src/Generated/Models/InternalRunObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunObjectObject : IEquatable { private readonly string _value; + private const string ThreadRunValue = "thread.run"; public InternalRunObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadRunValue = "thread.run"; + _value = value; + } public static InternalRunObjectObject ThreadRun { get; } = new InternalRunObjectObject(ThreadRunValue); + public static bool operator ==(InternalRunObjectObject left, InternalRunObjectObject right) => left.Equals(right); + public static bool operator !=(InternalRunObjectObject left, InternalRunObjectObject right) => !left.Equals(right); + public static implicit operator InternalRunObjectObject(string value) => new InternalRunObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunObjectObject other && Equals(other); + public bool Equals(InternalRunObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.Serialization.cs b/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.Serialization.cs index 7e11cfd6a..27de37212 100644 --- a/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.Serialization.cs +++ b/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalRunObjectRequiredActionSubmitToolOutputs : IJsonM { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunObjectRequiredActionSubmitToolOutputs)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); - foreach (var item in ToolCalls) + foreach (InternalRequiredFunctionToolCall item in ToolCalls) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8Json } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,38 +56,35 @@ void IJsonModel.Write(Utf8Json #endif } } - writer.WriteEndObject(); } - InternalRunObjectRequiredActionSubmitToolOutputs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunObjectRequiredActionSubmitToolOutputs IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunObjectRequiredActionSubmitToolOutputs JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunObjectRequiredActionSubmitToolOutputs)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(document.RootElement, options); } - internal static InternalRunObjectRequiredActionSubmitToolOutputs DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunObjectRequiredActionSubmitToolOutputs DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IReadOnlyList toolCalls = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("tool_calls"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalRequiredFunctionToolCall.DeserializeInternalRequiredFunctionToolCall(item, options)); } @@ -90,18 +93,17 @@ internal static InternalRunObjectRequiredActionSubmitToolOutputs DeserializeInte } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunObjectRequiredActionSubmitToolOutputs(toolCalls, serializedAdditionalRawData); + return new InternalRunObjectRequiredActionSubmitToolOutputs(toolCalls, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -111,15 +113,16 @@ BinaryData IPersistableModel.W } } - InternalRunObjectRequiredActionSubmitToolOutputs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunObjectRequiredActionSubmitToolOutputs IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunObjectRequiredActionSubmitToolOutputs 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(document.RootElement, options); } default: @@ -129,15 +132,20 @@ InternalRunObjectRequiredActionSubmitToolOutputs IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunObjectRequiredActionSubmitToolOutputs FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunObjectRequiredActionSubmitToolOutputs internalRunObjectRequiredActionSubmitToolOutputs) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(document.RootElement); + if (internalRunObjectRequiredActionSubmitToolOutputs == null) + { + return null; + } + return BinaryContent.Create(internalRunObjectRequiredActionSubmitToolOutputs, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunObjectRequiredActionSubmitToolOutputs(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.cs b/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.cs index 4897be504..ea44705be 100644 --- a/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.cs +++ b/src/Generated/Models/InternalRunObjectRequiredActionSubmitToolOutputs.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunObjectRequiredActionSubmitToolOutputs { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunObjectRequiredActionSubmitToolOutputs() { ToolCalls = new ChangeTrackingList(); } - internal InternalRunObjectRequiredActionSubmitToolOutputs(IReadOnlyList toolCalls, IDictionary serializedAdditionalRawData) + internal InternalRunObjectRequiredActionSubmitToolOutputs(IReadOnlyList toolCalls, IDictionary additionalBinaryDataProperties) { ToolCalls = toolCalls; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IReadOnlyList ToolCalls { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunObjectRequiredActionType.cs b/src/Generated/Models/InternalRunObjectRequiredActionType.cs index bd53c3266..d5c50136a 100644 --- a/src/Generated/Models/InternalRunObjectRequiredActionType.cs +++ b/src/Generated/Models/InternalRunObjectRequiredActionType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunObjectRequiredActionType : IEquatable { private readonly string _value; + private const string SubmitToolOutputsValue = "submit_tool_outputs"; public InternalRunObjectRequiredActionType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string SubmitToolOutputsValue = "submit_tool_outputs"; + _value = value; + } public static InternalRunObjectRequiredActionType SubmitToolOutputs { get; } = new InternalRunObjectRequiredActionType(SubmitToolOutputsValue); + public static bool operator ==(InternalRunObjectRequiredActionType left, InternalRunObjectRequiredActionType right) => left.Equals(right); + public static bool operator !=(InternalRunObjectRequiredActionType left, InternalRunObjectRequiredActionType right) => !left.Equals(right); + public static implicit operator InternalRunObjectRequiredActionType(string value) => new InternalRunObjectRequiredActionType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunObjectRequiredActionType other && Equals(other); + public bool Equals(InternalRunObjectRequiredActionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRunRequiredAction.Serialization.cs b/src/Generated/Models/InternalRunRequiredAction.Serialization.cs index 67fe40abc..34c1dad54 100644 --- a/src/Generated/Models/InternalRunRequiredAction.Serialization.cs +++ b/src/Generated/Models/InternalRunRequiredAction.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunRequiredAction : IJsonModel { + internal InternalRunRequiredAction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunRequiredAction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteObjectValue(Type, options); - } - if (SerializedAdditionalRawData?.ContainsKey("submit_tool_outputs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("submit_tool_outputs") != true) { writer.WritePropertyName("submit_tool_outputs"u8); writer.WriteObjectValue(SubmitToolOutputs, options); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("type"u8); + writer.WriteObjectValue(Type, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - InternalRunRequiredAction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunRequiredAction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunRequiredAction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunRequiredAction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunRequiredAction(document.RootElement, options); } - internal static InternalRunRequiredAction DeserializeInternalRunRequiredAction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunRequiredAction DeserializeInternalRunRequiredAction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - object type = default; InternalRunObjectRequiredActionSubmitToolOutputs submitToolOutputs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + object @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("submit_tool_outputs"u8)) { - type = property.Value.GetObject(); + submitToolOutputs = InternalRunObjectRequiredActionSubmitToolOutputs.DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(prop.Value, options); continue; } - if (property.NameEquals("submit_tool_outputs"u8)) + if (prop.NameEquals("type"u8)) { - submitToolOutputs = InternalRunObjectRequiredActionSubmitToolOutputs.DeserializeInternalRunObjectRequiredActionSubmitToolOutputs(property.Value, options); + @type = prop.Value.GetObject(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunRequiredAction(type, submitToolOutputs, serializedAdditionalRawData); + return new InternalRunRequiredAction(submitToolOutputs, @type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - InternalRunRequiredAction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunRequiredAction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunRequiredAction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunRequiredAction(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalRunRequiredAction IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunRequiredAction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunRequiredAction internalRunRequiredAction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunRequiredAction(document.RootElement); + if (internalRunRequiredAction == null) + { + return null; + } + return BinaryContent.Create(internalRunRequiredAction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunRequiredAction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunRequiredAction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunRequiredAction.cs b/src/Generated/Models/InternalRunRequiredAction.cs index 627dd8b84..ea41c0060 100644 --- a/src/Generated/Models/InternalRunRequiredAction.cs +++ b/src/Generated/Models/InternalRunRequiredAction.cs @@ -9,25 +9,26 @@ namespace OpenAI.Assistants { internal partial class InternalRunRequiredAction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunRequiredAction(InternalRunObjectRequiredActionSubmitToolOutputs submitToolOutputs) { - Argument.AssertNotNull(submitToolOutputs, nameof(submitToolOutputs)); - SubmitToolOutputs = submitToolOutputs; } - internal InternalRunRequiredAction(object type, InternalRunObjectRequiredActionSubmitToolOutputs submitToolOutputs, IDictionary serializedAdditionalRawData) + internal InternalRunRequiredAction(InternalRunObjectRequiredActionSubmitToolOutputs submitToolOutputs, object @type, IDictionary additionalBinaryDataProperties) { - Type = type; SubmitToolOutputs = submitToolOutputs; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalRunRequiredAction() + public InternalRunObjectRequiredActionSubmitToolOutputs SubmitToolOutputs { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public InternalRunObjectRequiredActionSubmitToolOutputs SubmitToolOutputs { get; } } } diff --git a/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.Serialization.cs b/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.Serialization.cs index 84313365a..747bb9d1b 100644 --- a/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.Serialization.cs +++ b/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepCodeInterpreterLogOutput : IJsonModel { + internal InternalRunStepCodeInterpreterLogOutput() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepCodeInterpreterLogOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("logs") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("logs") != true) { writer.WritePropertyName("logs"u8); writer.WriteStringValue(InternalLogs); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepCodeInterpreterLogOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepCodeInterpreterLogOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepCodeInterpreterLogOutput)JsonModelCreateCore(ref reader, options); + + protected override RunStepCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepCodeInterpreterLogOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepCodeInterpreterLogOutput(document.RootElement, options); } - internal static InternalRunStepCodeInterpreterLogOutput DeserializeInternalRunStepCodeInterpreterLogOutput(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepCodeInterpreterLogOutput DeserializeInternalRunStepCodeInterpreterLogOutput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string logs = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "logs"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string internalLogs = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("logs"u8)) + if (prop.NameEquals("type"u8)) { - logs = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("logs"u8)) { - type = property.Value.GetString(); + internalLogs = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepCodeInterpreterLogOutput(type, serializedAdditionalRawData, logs); + return new InternalRunStepCodeInterpreterLogOutput(@type, additionalBinaryDataProperties, internalLogs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(Mode } } - InternalRunStepCodeInterpreterLogOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepCodeInterpreterLogOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepCodeInterpreterLogOutput)PersistableModelCreateCore(data, options); + protected override RunStepCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepCodeInterpreterLogOutput(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalRunStepCodeInterpreterLogOutput IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepCodeInterpreterLogOutput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepCodeInterpreterLogOutput internalRunStepCodeInterpreterLogOutput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepCodeInterpreterLogOutput(document.RootElement); + if (internalRunStepCodeInterpreterLogOutput == null) + { + return null; + } + return BinaryContent.Create(internalRunStepCodeInterpreterLogOutput, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepCodeInterpreterLogOutput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepCodeInterpreterLogOutput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.cs b/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.cs index a44f25f41..20134cd52 100644 --- a/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.cs +++ b/src/Generated/Models/InternalRunStepCodeInterpreterLogOutput.cs @@ -9,21 +9,14 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepCodeInterpreterLogOutput : RunStepCodeInterpreterOutput { - internal InternalRunStepCodeInterpreterLogOutput(string internalLogs) + internal InternalRunStepCodeInterpreterLogOutput(string internalLogs) : base("logs") { - Argument.AssertNotNull(internalLogs, nameof(internalLogs)); - - Type = "logs"; InternalLogs = internalLogs; } - internal InternalRunStepCodeInterpreterLogOutput(string type, IDictionary serializedAdditionalRawData, string internalLogs) : base(type, serializedAdditionalRawData) + internal InternalRunStepCodeInterpreterLogOutput(string @type, IDictionary additionalBinaryDataProperties, string internalLogs) : base(@type, additionalBinaryDataProperties) { InternalLogs = internalLogs; } - - internal InternalRunStepCodeInterpreterLogOutput() - { - } } } diff --git a/src/Generated/Models/InternalRunStepDelta.Serialization.cs b/src/Generated/Models/InternalRunStepDelta.Serialization.cs index 3b6d44463..62f763820 100644 --- a/src/Generated/Models/InternalRunStepDelta.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDelta.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDelta : IJsonModel { + internal InternalRunStepDelta() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteObjectValue(Object, options); - } - if (SerializedAdditionalRawData?.ContainsKey("delta") != true) + if (_additionalBinaryDataProperties?.ContainsKey("delta") != true) { writer.WritePropertyName("delta"u8); writer.WriteObjectValue(Delta, options); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("object"u8); + writer.WriteObjectValue(this.Object, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr #endif } } - writer.WriteEndObject(); } - InternalRunStepDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDelta JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDelta(document.RootElement, options); } - internal static InternalRunStepDelta DeserializeInternalRunStepDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDelta DeserializeInternalRunStepDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - object @object = default; InternalRunStepDeltaObjectDelta delta = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + object @object = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("delta"u8)) { - @object = property.Value.GetObject(); + delta = InternalRunStepDeltaObjectDelta.DeserializeInternalRunStepDeltaObjectDelta(prop.Value, options); continue; } - if (property.NameEquals("delta"u8)) + if (prop.NameEquals("object"u8)) { - delta = InternalRunStepDeltaObjectDelta.DeserializeInternalRunStepDeltaObjectDelta(property.Value, options); + @object = prop.Value.GetObject(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDelta(id, @object, delta, serializedAdditionalRawData); + return new InternalRunStepDelta(id, delta, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - InternalRunStepDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDelta 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDelta(document.RootElement, options); } default: @@ -141,15 +148,20 @@ InternalRunStepDelta IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDelta internalRunStepDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDelta(document.RootElement); + if (internalRunStepDelta == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDelta, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDelta.cs b/src/Generated/Models/InternalRunStepDelta.cs index 55d73464a..2734d84a0 100644 --- a/src/Generated/Models/InternalRunStepDelta.cs +++ b/src/Generated/Models/InternalRunStepDelta.cs @@ -9,30 +9,30 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDelta { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDelta(string id, InternalRunStepDeltaObjectDelta delta) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(delta, nameof(delta)); - Id = id; Delta = delta; } - internal InternalRunStepDelta(string id, object @object, InternalRunStepDeltaObjectDelta delta, IDictionary serializedAdditionalRawData) + internal InternalRunStepDelta(string id, InternalRunStepDeltaObjectDelta delta, object @object, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; Delta = delta; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRunStepDelta() - { + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public InternalRunStepDeltaObjectDelta Delta { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaObjectDelta.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaObjectDelta.Serialization.cs index b3430a127..a0765a8d4 100644 --- a/src/Generated/Models/InternalRunStepDeltaObjectDelta.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaObjectDelta.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ internal partial class InternalRunStepDeltaObjectDelta : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaObjectDelta)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("step_details") != true && Optional.IsDefined(StepDetails)) + if (Optional.IsDefined(StepDetails) && _additionalBinaryDataProperties?.ContainsKey("step_details") != true) { writer.WritePropertyName("step_details"u8); writer.WriteObjectValue(StepDetails, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,57 +51,53 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalRunStepDeltaObjectDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaObjectDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaObjectDelta JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaObjectDelta)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaObjectDelta(document.RootElement, options); } - internal static InternalRunStepDeltaObjectDelta DeserializeInternalRunStepDeltaObjectDelta(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaObjectDelta DeserializeInternalRunStepDeltaObjectDelta(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalRunStepDeltaStepDetails stepDetails = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("step_details"u8)) + if (prop.NameEquals("step_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - stepDetails = InternalRunStepDeltaStepDetails.DeserializeInternalRunStepDeltaStepDetails(property.Value, options); + stepDetails = InternalRunStepDeltaStepDetails.DeserializeInternalRunStepDeltaStepDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaObjectDelta(stepDetails, serializedAdditionalRawData); + return new InternalRunStepDeltaObjectDelta(stepDetails, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -105,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalRunStepDeltaObjectDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaObjectDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaObjectDelta 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaObjectDelta(document.RootElement, options); } default: @@ -123,15 +126,20 @@ InternalRunStepDeltaObjectDelta IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaObjectDelta FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaObjectDelta internalRunStepDeltaObjectDelta) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaObjectDelta(document.RootElement); + if (internalRunStepDeltaObjectDelta == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaObjectDelta, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaObjectDelta(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaObjectDelta(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaObjectDelta.cs b/src/Generated/Models/InternalRunStepDeltaObjectDelta.cs index 1faf845db..127abc57c 100644 --- a/src/Generated/Models/InternalRunStepDeltaObjectDelta.cs +++ b/src/Generated/Models/InternalRunStepDeltaObjectDelta.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaObjectDelta { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaObjectDelta() { } - internal InternalRunStepDeltaObjectDelta(InternalRunStepDeltaStepDetails stepDetails, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaObjectDelta(InternalRunStepDeltaStepDetails stepDetails, IDictionary additionalBinaryDataProperties) { StepDetails = stepDetails; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalRunStepDeltaStepDetails StepDetails { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaObjectObject.cs b/src/Generated/Models/InternalRunStepDeltaObjectObject.cs index ea17969d2..9e63f1475 100644 --- a/src/Generated/Models/InternalRunStepDeltaObjectObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunStepDeltaObjectObject : IEquatable { private readonly string _value; + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; public InternalRunStepDeltaObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + _value = value; + } public static InternalRunStepDeltaObjectObject ThreadRunStepDelta { get; } = new InternalRunStepDeltaObjectObject(ThreadRunStepDeltaValue); + public static bool operator ==(InternalRunStepDeltaObjectObject left, InternalRunStepDeltaObjectObject right) => left.Equals(right); + public static bool operator !=(InternalRunStepDeltaObjectObject left, InternalRunStepDeltaObjectObject right) => !left.Equals(right); + public static implicit operator InternalRunStepDeltaObjectObject(string value) => new InternalRunStepDeltaObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunStepDeltaObjectObject other && Equals(other); + public bool Equals(InternalRunStepDeltaObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetails.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetails.Serialization.cs index 6ba369d00..43c72487a 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetails.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetails.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepDeltaStepDetails))] - internal partial class InternalRunStepDeltaStepDetails : IJsonModel + internal abstract partial class InternalRunStepDeltaStepDetails : IJsonModel { + internal InternalRunStepDeltaStepDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetails(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetails DeserializeInternalRunStepDeltaStepDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetails DeserializeInternalRunStepDeltaStepDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "message_creation": return InternalRunStepDeltaStepDetailsMessageCreationObject.DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(element, options); - case "tool_calls": return InternalRunStepDeltaStepDetailsToolCallsObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(element, options); + case "message_creation": + return InternalRunStepDeltaStepDetailsMessageCreationObject.DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(element, options); + case "tool_calls": + return InternalRunStepDeltaStepDetailsToolCallsObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(element, options); } } return UnknownRunStepDeltaStepDetails.DeserializeUnknownRunStepDeltaStepDetails(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalRunStepDeltaStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetails(document.RootElement, options); } default: @@ -110,15 +122,20 @@ InternalRunStepDeltaStepDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetails internalRunStepDeltaStepDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetails(document.RootElement); + if (internalRunStepDeltaStepDetails == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetails.cs b/src/Generated/Models/InternalRunStepDeltaStepDetails.cs index 987886798..b1e8bee11 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetails.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetails.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal abstract partial class InternalRunStepDeltaStepDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalRunStepDeltaStepDetails() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalRunStepDeltaStepDetails(string @type) { + Type = @type; } - internal InternalRunStepDeltaStepDetails(string type, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetails(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.Serialization.cs index 0c0825062..5ff003063 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,99 +15,77 @@ internal partial class InternalRunStepDeltaStepDetailsMessageCreationObject : IJ { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsMessageCreationObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("message_creation") != true && Optional.IsDefined(MessageCreation)) + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(MessageCreation) && _additionalBinaryDataProperties?.ContainsKey("message_creation") != true) { writer.WritePropertyName("message_creation"u8); writer.WriteObjectValue(MessageCreation, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsMessageCreationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsMessageCreationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsMessageCreationObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsMessageCreationObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsMessageCreationObject DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsMessageCreationObject DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "message_creation"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation messageCreation = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("message_creation"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - messageCreation = InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("message_creation"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + messageCreation = InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsMessageCreationObject(type, serializedAdditionalRawData, messageCreation); + return new InternalRunStepDeltaStepDetailsMessageCreationObject(@type, additionalBinaryDataProperties, messageCreation); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -116,15 +95,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsMessageCreationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsMessageCreationObject)PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(document.RootElement, options); } default: @@ -134,15 +114,20 @@ InternalRunStepDeltaStepDetailsMessageCreationObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsMessageCreationObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsMessageCreationObject internalRunStepDeltaStepDetailsMessageCreationObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(document.RootElement); + if (internalRunStepDeltaStepDetailsMessageCreationObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsMessageCreationObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsMessageCreationObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.cs index 0ee0b50a4..9faa536c5 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObject.cs @@ -9,12 +9,11 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsMessageCreationObject : InternalRunStepDeltaStepDetails { - internal InternalRunStepDeltaStepDetailsMessageCreationObject() + internal InternalRunStepDeltaStepDetailsMessageCreationObject() : base("message_creation") { - Type = "message_creation"; } - internal InternalRunStepDeltaStepDetailsMessageCreationObject(string type, IDictionary serializedAdditionalRawData, InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation messageCreation) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsMessageCreationObject(string @type, IDictionary additionalBinaryDataProperties, InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation messageCreation) : base(@type, additionalBinaryDataProperties) { MessageCreation = messageCreation; } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.Serialization.cs index 24e660350..5655786b7 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ internal partial class InternalRunStepDeltaStepDetailsMessageCreationObjectMessa { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("message_id") != true && Optional.IsDefined(MessageId)) + if (Optional.IsDefined(MessageId) && _additionalBinaryDataProperties?.ContainsKey("message_id") != true) { writer.WritePropertyName("message_id"u8); writer.WriteStringValue(MessageId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string messageId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("message_id"u8)) + if (prop.NameEquals("message_id"u8)) { - messageId = property.Value.GetString(); + messageId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(messageId, serializedAdditionalRawData); + return new InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(messageId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +103,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(document.RootElement, options); } default: @@ -119,15 +122,20 @@ InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation IPersistable string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation internalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(document.RootElement); + if (internalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.cs index 812f249c3..116867802 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation() { } - internal InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(string messageId, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation(string messageId, IDictionary additionalBinaryDataProperties) { MessageId = messageId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string MessageId { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.Serialization.cs index 0b67792c5..ce626cea9 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.Serialization.cs @@ -7,128 +7,111 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsCodeObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsCodeObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsCodeObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsCodeObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsCodeObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsCodeObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsCodeObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "code_interpreter"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string id = default; InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("index"u8)) { - id = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - codeInterpreter = InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsCodeObject(type, serializedAdditionalRawData, index, id, codeInterpreter); + return new InternalRunStepDeltaStepDetailsToolCallsCodeObject(@type, additionalBinaryDataProperties, index, id, codeInterpreter); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -138,15 +121,16 @@ BinaryData IPersistableModel } } - InternalRunStepDeltaStepDetailsToolCallsCodeObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsCodeObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeObject)PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(document.RootElement, options); } default: @@ -156,15 +140,20 @@ InternalRunStepDeltaStepDetailsToolCallsCodeObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsCodeObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsCodeObject internalRunStepDeltaStepDetailsToolCallsCodeObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsCodeObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsCodeObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsCodeObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.cs index ccd8ec23b..232eaacc8 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObject.cs @@ -9,25 +9,22 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeObject : InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject { - internal InternalRunStepDeltaStepDetailsToolCallsCodeObject(int index) + internal InternalRunStepDeltaStepDetailsToolCallsCodeObject(int index) : base("code_interpreter") { - Type = "code_interpreter"; Index = index; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeObject(string type, IDictionary serializedAdditionalRawData, int index, string id, InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsCodeObject(string @type, IDictionary additionalBinaryDataProperties, int index, string id, InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(@type, additionalBinaryDataProperties) { Index = index; Id = id; CodeInterpreter = codeInterpreter; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeObject() - { - } - public int Index { get; } + public string Id { get; } + public InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter CodeInterpreter { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs index 716f63607..241f9bf57 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,36 @@ internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInt { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("input") != true && Optional.IsDefined(Input)) + if (Optional.IsDefined(Input) && _additionalBinaryDataProperties?.ContainsKey("input") != true) { writer.WritePropertyName("input"u8); writer.WriteStringValue(Input); } - if (SerializedAdditionalRawData?.ContainsKey("outputs") != true && true && Optional.IsCollectionDefined(Outputs)) + if (true && Optional.IsCollectionDefined(Outputs) && _additionalBinaryDataProperties?.ContainsKey("outputs") != true) { writer.WritePropertyName("outputs"u8); writer.WriteStartArray(); - foreach (var item in Outputs) + foreach (RunStepUpdateCodeInterpreterOutput item in Outputs) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string input = default; IReadOnlyList outputs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("input"u8)) + if (prop.NameEquals("input"u8)) { - input = property.Value.GetString(); + input = prop.Value.GetString(); continue; } - if (property.NameEquals("outputs"u8)) + if (prop.NameEquals("outputs"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(RunStepUpdateCodeInterpreterOutput.DeserializeRunStepUpdateCodeInterpreterOutput(item, options)); } @@ -105,18 +108,17 @@ internal static InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterprete } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(input, outputs ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(input, outputs ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -126,15 +128,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, options); } default: @@ -144,15 +147,20 @@ InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter IPersistableMo string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter internalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.cs index 2330d340a..46ffaab59 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter.cs @@ -4,25 +4,34 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter() { Outputs = new ChangeTrackingList(); } - internal InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(string input, IReadOnlyList outputs, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter(string input, IReadOnlyList outputs, IDictionary additionalBinaryDataProperties) { Input = input; Outputs = outputs; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Input { get; } + public IReadOnlyList Outputs { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.Serialization.cs index 2e1725b51..019556250 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.Serialization.cs @@ -7,117 +7,100 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("image") != true && Optional.IsDefined(Image)) + if (Optional.IsDefined(Image) && _additionalBinaryDataProperties?.ContainsKey("image") != true) { writer.WritePropertyName("image"u8); writer.WriteObjectValue(Image, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepUpdateCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "image"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage image = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("image"u8)) + if (prop.NameEquals("index"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - image = InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(property.Value, options); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("image"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + image = InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(type, serializedAdditionalRawData, index, image); + return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(@type, additionalBinaryDataProperties, index, image); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -127,15 +110,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject)PersistableModelCreateCore(data, options); + protected override RunStepUpdateCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(document.RootElement, options); } default: @@ -145,15 +129,20 @@ InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject IPersistableModel< string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.cs index 26acd5b75..76500ee8d 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.cs @@ -9,23 +9,19 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject : RunStepUpdateCodeInterpreterOutput { - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(int index) + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(int index) : base("image") { - Type = "image"; Index = index; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(string type, IDictionary serializedAdditionalRawData, int index, InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage image) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(string @type, IDictionary additionalBinaryDataProperties, int index, InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage image) : base(@type, additionalBinaryDataProperties) { Index = index; Image = image; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject() - { - } - public int Index { get; } + public InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage Image { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs index 9ad45a123..55c28ee7b 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageOb { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true && Optional.IsDefined(FileId)) + if (Optional.IsDefined(FileId) && _additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(fileId, serializedAdditionalRawData); + return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(fileId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +103,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, options); } default: @@ -119,15 +122,20 @@ InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage IPersistableM string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.cs index cd41fb9fa..19daf4e7e 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage() { } - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(string fileId, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage(string fileId, IDictionary additionalBinaryDataProperties) { FileId = fileId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.Serialization.cs index 0047ba1a9..829a1d703 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.Serialization.cs @@ -7,113 +7,96 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("logs") != true && Optional.IsDefined(InternalLogs)) + if (Optional.IsDefined(InternalLogs) && _additionalBinaryDataProperties?.ContainsKey("logs") != true) { writer.WritePropertyName("logs"u8); writer.WriteStringValue(InternalLogs); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepUpdateCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "logs"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; - string logs = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string internalLogs = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("logs"u8)) + if (prop.NameEquals("index"u8)) { - logs = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("logs"u8)) { - type = property.Value.GetString(); + internalLogs = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(type, serializedAdditionalRawData, index, logs); + return new InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(@type, additionalBinaryDataProperties, index, internalLogs); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +106,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject)PersistableModelCreateCore(data, options); + protected override RunStepUpdateCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(document.RootElement, options); } default: @@ -141,15 +125,20 @@ InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject internalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.cs index aa0e9501d..37998b442 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.cs @@ -9,22 +9,17 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject : RunStepUpdateCodeInterpreterOutput { - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(int index) + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(int index) : base("logs") { - Type = "logs"; Index = index; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(string type, IDictionary serializedAdditionalRawData, int index, string internalLogs) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(string @type, IDictionary additionalBinaryDataProperties, int index, string internalLogs) : base(@type, additionalBinaryDataProperties) { Index = index; InternalLogs = internalLogs; } - internal InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject() - { - } - public int Index { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.Serialization.cs index 194edb5b5..b58e9c1fa 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.Serialization.cs @@ -7,124 +7,107 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFileSearchObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsFileSearchObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsFileSearchObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsFileSearchObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsFileSearchObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsFileSearchObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsFileSearchObject DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsFileSearchObject DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "file_search"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string id = default; InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch fileSearch = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("index"u8)) { - id = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("id"u8)) { - fileSearch = InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("file_search"u8)) { - type = property.Value.GetString(); + fileSearch = InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(type, serializedAdditionalRawData, index, id, fileSearch); + return new InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(@type, additionalBinaryDataProperties, index, id, fileSearch); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +117,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsFileSearchObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsFileSearchObject)PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(document.RootElement, options); } default: @@ -152,15 +136,20 @@ InternalRunStepDeltaStepDetailsToolCallsFileSearchObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsFileSearchObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsFileSearchObject internalRunStepDeltaStepDetailsToolCallsFileSearchObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsFileSearchObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsFileSearchObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.cs index 10ebb17ab..b0da34cf3 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.cs @@ -9,28 +9,23 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFileSearchObject : InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject { - internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(int index, InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) + internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(int index, InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base("file_search") { - Argument.AssertNotNull(fileSearch, nameof(fileSearch)); - - Type = "file_search"; Index = index; FileSearch = fileSearch; } - internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(string type, IDictionary serializedAdditionalRawData, int index, string id, InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject(string @type, IDictionary additionalBinaryDataProperties, int index, string id, InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(@type, additionalBinaryDataProperties) { Index = index; Id = id; FileSearch = fileSearch; } - internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObject() - { - } - public int Index { get; } + public string Id { get; } + public InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch FileSearch { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs index 9b40ed142..6b443b8b1 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,36 @@ internal partial class InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectF { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("ranking_options") != true && Optional.IsDefined(RankingOptions)) - { - writer.WritePropertyName("ranking_options"u8); - writer.WriteObjectValue(RankingOptions, options); - } - if (SerializedAdditionalRawData?.ContainsKey("results") != true && true && Optional.IsCollectionDefined(Results)) + if (true && Optional.IsCollectionDefined(Results) && _additionalBinaryDataProperties?.ContainsKey("results") != true) { writer.WritePropertyName("results"u8); writer.WriteStartArray(); - foreach (var item in Results) + foreach (RunStepFileSearchResult item in Results) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(RankingOptions) && _additionalBinaryDataProperties?.ContainsKey("ranking_options") != true) + { + writer.WritePropertyName("ranking_options"u8); + writer.WriteObjectValue(RankingOptions, options); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - FileSearchRankingOptions rankingOptions = default; IReadOnlyList results = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + FileSearchRankingOptions rankingOptions = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("ranking_options"u8)) + if (prop.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(property.Value, options); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(RunStepFileSearchResult.DeserializeRunStepFileSearchResult(item, options)); + } + results = array; continue; } - if (property.NameEquals("results"u8)) + if (prop.NameEquals("ranking_options"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(RunStepFileSearchResult.DeserializeRunStepFileSearchResult(item, options)); - } - results = array; + rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(rankingOptions, results ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(results ?? new ChangeTrackingList(), rankingOptions, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -130,15 +132,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, options); } default: @@ -148,15 +151,20 @@ InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch IPersistableM string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch internalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.cs index 682eacb7f..610b1286c 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch.cs @@ -4,23 +4,32 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch() { Results = new ChangeTrackingList(); } - internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(FileSearchRankingOptions rankingOptions, IReadOnlyList results, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch(IReadOnlyList results, FileSearchRankingOptions rankingOptions, IDictionary additionalBinaryDataProperties) { - RankingOptions = rankingOptions; Results = results; - SerializedAdditionalRawData = serializedAdditionalRawData; + RankingOptions = rankingOptions; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public IReadOnlyList Results { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.Serialization.cs index 66776a57d..a15bf2fe0 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.Serialization.cs @@ -7,128 +7,111 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFunctionObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsFunctionObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) + if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("function") != true && Optional.IsDefined(Function)) + if (Optional.IsDefined(Function) && _additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsFunctionObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsFunctionObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObject DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObject DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "function"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); int index = default; string id = default; InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction function = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("type"u8)) { - index = property.Value.GetInt32(); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("index"u8)) { - id = property.Value.GetString(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - function = InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("function"u8)) { - type = property.Value.GetString(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + function = InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsFunctionObject(type, serializedAdditionalRawData, index, id, function); + return new InternalRunStepDeltaStepDetailsToolCallsFunctionObject(@type, additionalBinaryDataProperties, index, id, function); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -138,15 +121,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsFunctionObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsFunctionObject)PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(document.RootElement, options); } default: @@ -156,15 +140,20 @@ InternalRunStepDeltaStepDetailsToolCallsFunctionObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsFunctionObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsFunctionObject internalRunStepDeltaStepDetailsToolCallsFunctionObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsFunctionObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsFunctionObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsFunctionObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.cs index e45ecae14..403afcb1b 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObject.cs @@ -9,25 +9,22 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFunctionObject : InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject { - internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject(int index) + internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject(int index) : base("function") { - Type = "function"; Index = index; } - internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject(string type, IDictionary serializedAdditionalRawData, int index, string id, InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction function) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject(string @type, IDictionary additionalBinaryDataProperties, int index, string id, InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction function) : base(@type, additionalBinaryDataProperties) { Index = index; Id = id; Function = function; } - internal InternalRunStepDeltaStepDetailsToolCallsFunctionObject() - { - } - public int Index { get; } + public string Id { get; } + public InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction Function { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.Serialization.cs index f96531c16..082734f3b 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,24 +15,29 @@ internal partial class InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFun { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true && Optional.IsDefined(Arguments)) + if (Optional.IsDefined(Arguments) && _additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData?.ContainsKey("output") != true && Optional.IsDefined(Output)) + if (Optional.IsDefined(Output) && _additionalBinaryDataProperties?.ContainsKey("output") != true) { if (Output != null) { @@ -40,12 +46,12 @@ void IJsonModel. } else { - writer.WriteNull("output"); + writer.WriteNull("output"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +59,7 @@ void IJsonModel. } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,25 +68,23 @@ void IJsonModel. #endif } } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -88,44 +92,42 @@ internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction D string name = default; string arguments = default; string output = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - arguments = property.Value.GetString(); + arguments = prop.Value.GetString(); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("output"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { output = null; continue; } - output = property.Value.GetString(); + output = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(name, arguments, output, serializedAdditionalRawData); + return new InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(name, arguments, output, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +137,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(document.RootElement, options); } default: @@ -153,15 +156,20 @@ InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction internalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.cs index e546c4f89..d60c9a6cc 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction.cs @@ -9,21 +9,30 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction() { } - internal InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(string name, string arguments, string output, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction(string name, string arguments, string output, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; Output = output; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; } + public string Arguments { get; } + public string Output { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.Serialization.cs index b1ba9cfad..4c7d10c26 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,109 +15,87 @@ internal partial class InternalRunStepDeltaStepDetailsToolCallsObject : IJsonMod { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true && Optional.IsCollectionDefined(ToolCalls)) + base.JsonModelWriteCore(writer, options); + if (Optional.IsCollectionDefined(ToolCalls) && _additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); - foreach (var item in ToolCalls) + foreach (InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject item in ToolCalls) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsObject)JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList toolCalls = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "tool_calls"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + IList toolCalls = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + @type = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("tool_calls"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(item, options)); } toolCalls = array; continue; } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDeltaStepDetailsToolCallsObject(type, serializedAdditionalRawData, toolCalls ?? new ChangeTrackingList()); + return new InternalRunStepDeltaStepDetailsToolCallsObject(@type, additionalBinaryDataProperties, toolCalls ?? new ChangeTrackingList()); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -126,15 +105,16 @@ BinaryData IPersistableModel.Wri } } - InternalRunStepDeltaStepDetailsToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDeltaStepDetailsToolCallsObject)PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(document.RootElement, options); } default: @@ -144,15 +124,20 @@ InternalRunStepDeltaStepDetailsToolCallsObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDeltaStepDetailsToolCallsObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsObject internalRunStepDeltaStepDetailsToolCallsObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.cs index bae1ef100..20bc75d39 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObject.cs @@ -4,22 +4,22 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDeltaStepDetailsToolCallsObject : InternalRunStepDeltaStepDetails { - internal InternalRunStepDeltaStepDetailsToolCallsObject() + internal InternalRunStepDeltaStepDetailsToolCallsObject() : base("tool_calls") { - Type = "tool_calls"; ToolCalls = new ChangeTrackingList(); } - internal InternalRunStepDeltaStepDetailsToolCallsObject(string type, IDictionary serializedAdditionalRawData, IReadOnlyList toolCalls) : base(type, serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsObject(string @type, IDictionary additionalBinaryDataProperties, IList toolCalls) : base(@type, additionalBinaryDataProperties) { ToolCalls = toolCalls; } - public IReadOnlyList ToolCalls { get; } + public IList ToolCalls { get; } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs index f9aa10e1a..89ea067c0 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject))] - internal partial class InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject : IJsonModel + internal abstract partial class InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject : IJsonModel { + internal InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.W } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,45 +55,47 @@ void IJsonModel.W #endif } } - writer.WriteEndObject(); } - InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement, options); } - internal static InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "code_interpreter": return InternalRunStepDeltaStepDetailsToolCallsCodeObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(element, options); - case "file_search": return InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(element, options); - case "function": return InternalRunStepDeltaStepDetailsToolCallsFunctionObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(element, options); + case "code_interpreter": + return InternalRunStepDeltaStepDetailsToolCallsCodeObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeObject(element, options); + case "file_search": + return InternalRunStepDeltaStepDetailsToolCallsFileSearchObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsFileSearchObject(element, options); + case "function": + return InternalRunStepDeltaStepDetailsToolCallsFunctionObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsFunctionObject(element, options); } } return UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.DeserializeUnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -93,15 +105,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement, options); } default: @@ -111,15 +124,20 @@ InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IPersistableModel< string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject internalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement); + if (internalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs index 55b7f0b45..ac05b64a0 100644 --- a/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs +++ b/src/Generated/Models/InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { internal abstract partial class InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject() + private protected IDictionary _additionalBinaryDataProperties; + + private protected InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(string @type) { + Type = @type; } - internal InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(string type, IDictionary serializedAdditionalRawData) + internal InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.Serialization.cs index 8f037505f..70ac2892d 100644 --- a/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsMessageCreationObject : IJsonModel { + internal InternalRunStepDetailsMessageCreationObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsMessageCreationObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("message_creation") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("message_creation") != true) { writer.WritePropertyName("message_creation"u8); writer.WriteObjectValue(_messageCreation, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsMessageCreationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsMessageCreationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsMessageCreationObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsMessageCreationObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsMessageCreationObject(document.RootElement, options); } - internal static InternalRunStepDetailsMessageCreationObject DeserializeInternalRunStepDetailsMessageCreationObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsMessageCreationObject DeserializeInternalRunStepDetailsMessageCreationObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "message_creation"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalRunStepDetailsMessageCreationObjectMessageCreation messageCreation = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("message_creation"u8)) + if (prop.NameEquals("type"u8)) { - messageCreation = InternalRunStepDetailsMessageCreationObjectMessageCreation.DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("message_creation"u8)) { - type = property.Value.GetString(); + messageCreation = InternalRunStepDetailsMessageCreationObjectMessageCreation.DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsMessageCreationObject(type, serializedAdditionalRawData, messageCreation); + return new InternalRunStepDetailsMessageCreationObject(@type, additionalBinaryDataProperties, messageCreation); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write( } } - InternalRunStepDetailsMessageCreationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsMessageCreationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsMessageCreationObject)PersistableModelCreateCore(data, options); + protected override RunStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsMessageCreationObject(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalRunStepDetailsMessageCreationObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsMessageCreationObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsMessageCreationObject internalRunStepDetailsMessageCreationObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsMessageCreationObject(document.RootElement); + if (internalRunStepDetailsMessageCreationObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsMessageCreationObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsMessageCreationObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsMessageCreationObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.cs b/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.cs index e36008494..0297b8f72 100644 --- a/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsMessageCreationObject.cs @@ -9,21 +9,14 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsMessageCreationObject : RunStepDetails { - internal InternalRunStepDetailsMessageCreationObject(InternalRunStepDetailsMessageCreationObjectMessageCreation messageCreation) + internal InternalRunStepDetailsMessageCreationObject(InternalRunStepDetailsMessageCreationObjectMessageCreation messageCreation) : base("message_creation") { - Argument.AssertNotNull(messageCreation, nameof(messageCreation)); - - Type = "message_creation"; _messageCreation = messageCreation; } - internal InternalRunStepDetailsMessageCreationObject(string type, IDictionary serializedAdditionalRawData, InternalRunStepDetailsMessageCreationObjectMessageCreation messageCreation) : base(type, serializedAdditionalRawData) + internal InternalRunStepDetailsMessageCreationObject(string @type, IDictionary additionalBinaryDataProperties, InternalRunStepDetailsMessageCreationObjectMessageCreation messageCreation) : base(@type, additionalBinaryDataProperties) { _messageCreation = messageCreation; } - - internal InternalRunStepDetailsMessageCreationObject() - { - } } } diff --git a/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.Serialization.cs index 4f0ef2047..863ffedb1 100644 --- a/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsMessageCreationObjectMessageCreation : IJsonModel { + internal InternalRunStepDetailsMessageCreationObjectMessageCreation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsMessageCreationObjectMessageCreation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("message_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message_id") != true) { writer.WritePropertyName("message_id"u8); writer.WriteStringValue(MessageId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Writ #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsMessageCreationObjectMessageCreation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsMessageCreationObjectMessageCreation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsMessageCreationObjectMessageCreation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsMessageCreationObjectMessageCreation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(document.RootElement, options); } - internal static InternalRunStepDetailsMessageCreationObjectMessageCreation DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsMessageCreationObjectMessageCreation DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string messageId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("message_id"u8)) + if (prop.NameEquals("message_id"u8)) { - messageId = property.Value.GetString(); + messageId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsMessageCreationObjectMessageCreation(messageId, serializedAdditionalRawData); + return new InternalRunStepDetailsMessageCreationObjectMessageCreation(messageId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsMessageCreationObjectMessageCreation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsMessageCreationObjectMessageCreation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalRunStepDetailsMessageCreationObjectMessageCreation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsMessageCreationObjectMessageCreation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsMessageCreationObjectMessageCreation internalRunStepDetailsMessageCreationObjectMessageCreation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(document.RootElement); + if (internalRunStepDetailsMessageCreationObjectMessageCreation == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsMessageCreationObjectMessageCreation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsMessageCreationObjectMessageCreation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsMessageCreationObjectMessageCreation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.cs b/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.cs index b876ff8c4..ecfcc7ded 100644 --- a/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.cs +++ b/src/Generated/Models/InternalRunStepDetailsMessageCreationObjectMessageCreation.cs @@ -9,24 +9,25 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsMessageCreationObjectMessageCreation { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsMessageCreationObjectMessageCreation(string messageId) { - Argument.AssertNotNull(messageId, nameof(messageId)); - MessageId = messageId; } - internal InternalRunStepDetailsMessageCreationObjectMessageCreation(string messageId, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsMessageCreationObjectMessageCreation(string messageId, IDictionary additionalBinaryDataProperties) { MessageId = messageId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalRunStepDetailsMessageCreationObjectMessageCreation() + public string MessageId { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string MessageId { get; } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.Serialization.cs index 60324912a..ee963279b 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeObject : IJsonModel { + internal InternalRunStepDetailsToolCallsCodeObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsCodeObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsCodeObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsCodeObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsCodeObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsCodeObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsCodeObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsCodeObject DeserializeInternalRunStepDetailsToolCallsCodeObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsCodeObject DeserializeInternalRunStepDetailsToolCallsCodeObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter = default; - RunStepToolCallKind type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.RunStepToolCallKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("id"u8)) { - codeInterpreter = InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToRunStepToolCallKind(); + kind = prop.Value.GetString().ToRunStepToolCallKind(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - id = property.Value.GetString(); + codeInterpreter = InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsCodeObject(type, id, serializedAdditionalRawData, codeInterpreter); + return new InternalRunStepDetailsToolCallsCodeObject(id, kind, additionalBinaryDataProperties, codeInterpreter); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalRunStepDetailsToolCallsCodeObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsCodeObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsCodeObject)PersistableModelCreateCore(data, options); + protected override RunStepToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsCodeObject(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRunStepDetailsToolCallsCodeObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsToolCallsCodeObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsCodeObject internalRunStepDetailsToolCallsCodeObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsCodeObject(document.RootElement); + if (internalRunStepDetailsToolCallsCodeObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsCodeObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsCodeObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsCodeObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.cs index f98b5c003..1901d9b3a 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObject.cs @@ -9,24 +9,16 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeObject : RunStepToolCall { - internal InternalRunStepDetailsToolCallsCodeObject(string id, InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(id) + internal InternalRunStepDetailsToolCallsCodeObject(string id, InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(id, Assistants.RunStepToolCallKind.CodeInterpreter) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(codeInterpreter, nameof(codeInterpreter)); - - Kind = RunStepToolCallKind.CodeInterpreter; CodeInterpreter = codeInterpreter; } - internal InternalRunStepDetailsToolCallsCodeObject(RunStepToolCallKind kind, string id, IDictionary serializedAdditionalRawData, InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(kind, id, serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsCodeObject(string id, Assistants.RunStepToolCallKind kind, IDictionary additionalBinaryDataProperties, InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter codeInterpreter) : base(id, kind, additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; } - internal InternalRunStepDetailsToolCallsCodeObject() - { - } - public InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter CodeInterpreter { get; } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs index 97ad03b81..cb8f8026b 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter : IJsonModel { + internal InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("input") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input") != true) { writer.WritePropertyName("input"u8); writer.WriteStringValue(Input); } - if (SerializedAdditionalRawData?.ContainsKey("outputs") != true && true) + if (true && _additionalBinaryDataProperties?.ContainsKey("outputs") != true) { writer.WritePropertyName("outputs"u8); writer.WriteStartArray(); - foreach (var item in Outputs) + foreach (RunStepCodeInterpreterOutput item in Outputs) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write( } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,44 +65,41 @@ void IJsonModel.Write( #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string input = default; IReadOnlyList outputs = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("input"u8)) + if (prop.NameEquals("input"u8)) { - input = property.Value.GetString(); + input = prop.Value.GetString(); continue; } - if (property.NameEquals("outputs"u8)) + if (prop.NameEquals("outputs"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(RunStepCodeInterpreterOutput.DeserializeRunStepCodeInterpreterOutput(item, options)); } @@ -101,18 +108,17 @@ internal static InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter Deseria } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(input, outputs, serializedAdditionalRawData); + return new InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(input, outputs, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -122,15 +128,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, options); } default: @@ -140,15 +147,20 @@ InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter internalRunStepDetailsToolCallsCodeObjectCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement); + if (internalRunStepDetailsToolCallsCodeObjectCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsCodeObjectCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.cs index e0b823ce9..4c6e6bd96 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter.cs @@ -4,32 +4,35 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(string input) { - Argument.AssertNotNull(input, nameof(input)); - Input = input; Outputs = new ChangeTrackingList(); } - internal InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(string input, IReadOnlyList outputs, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter(string input, IReadOnlyList outputs, IDictionary additionalBinaryDataProperties) { Input = input; Outputs = outputs; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Input { get; } + public IReadOnlyList Outputs { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.Serialization.cs index e0de2eb55..7b3184aff 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeOutputImageObject : IJsonModel { + internal InternalRunStepDetailsToolCallsCodeOutputImageObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsCodeOutputImageObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("image") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("image") != true) { writer.WritePropertyName("image"u8); writer.WriteObjectValue(_image, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsCodeOutputImageObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsCodeOutputImageObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsCodeOutputImageObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsCodeOutputImageObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsCodeOutputImageObject DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsCodeOutputImageObject DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "image"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalRunStepDetailsToolCallsCodeOutputImageObjectImage image = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("image"u8)) + if (prop.NameEquals("type"u8)) { - image = InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("image"u8)) { - type = property.Value.GetString(); + image = InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsCodeOutputImageObject(type, serializedAdditionalRawData, image); + return new InternalRunStepDetailsToolCallsCodeOutputImageObject(@type, additionalBinaryDataProperties, image); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsCodeOutputImageObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsCodeOutputImageObject)PersistableModelCreateCore(data, options); + protected override RunStepCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalRunStepDetailsToolCallsCodeOutputImageObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsToolCallsCodeOutputImageObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsCodeOutputImageObject internalRunStepDetailsToolCallsCodeOutputImageObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(document.RootElement); + if (internalRunStepDetailsToolCallsCodeOutputImageObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsCodeOutputImageObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsCodeOutputImageObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.cs index 2d12da18d..4f00f2f41 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObject.cs @@ -9,21 +9,14 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeOutputImageObject : RunStepCodeInterpreterOutput { - internal InternalRunStepDetailsToolCallsCodeOutputImageObject(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage image) + internal InternalRunStepDetailsToolCallsCodeOutputImageObject(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage image) : base("image") { - Argument.AssertNotNull(image, nameof(image)); - - Type = "image"; _image = image; } - internal InternalRunStepDetailsToolCallsCodeOutputImageObject(string type, IDictionary serializedAdditionalRawData, InternalRunStepDetailsToolCallsCodeOutputImageObjectImage image) : base(type, serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsCodeOutputImageObject(string @type, IDictionary additionalBinaryDataProperties, InternalRunStepDetailsToolCallsCodeOutputImageObjectImage image) : base(@type, additionalBinaryDataProperties) { _image = image; } - - internal InternalRunStepDetailsToolCallsCodeOutputImageObject() - { - } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs index 6e6ffba6a..1f2497850 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeOutputImageObjectImage : IJsonModel { + internal InternalRunStepDetailsToolCallsCodeOutputImageObjectImage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsCodeOutputImageObjectImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsCodeOutputImageObjectImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsToolCallsCodeOutputImageObjectImage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsCodeOutputImageObjectImage DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsCodeOutputImageObjectImage DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(fileId, serializedAdditionalRawData); + return new InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(fileId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsCodeOutputImageObjectImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsToolCallsCodeOutputImageObjectImage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, options); } default: @@ -119,15 +126,20 @@ InternalRunStepDetailsToolCallsCodeOutputImageObjectImage IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsToolCallsCodeOutputImageObjectImage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage internalRunStepDetailsToolCallsCodeOutputImageObjectImage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement); + if (internalRunStepDetailsToolCallsCodeOutputImageObjectImage == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsCodeOutputImageObjectImage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObjectImage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.cs index 17afb0073..e5a704b18 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsCodeOutputImageObjectImage.cs @@ -9,24 +9,25 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsCodeOutputImageObjectImage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(string fileId) { - Argument.AssertNotNull(fileId, nameof(fileId)); - FileId = fileId; } - internal InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(string fileId, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsCodeOutputImageObjectImage(string fileId, IDictionary additionalBinaryDataProperties) { FileId = fileId; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal InternalRunStepDetailsToolCallsCodeOutputImageObjectImage() + public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.Serialization.cs index 84429d458..c3383210e 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFileSearchObject : IJsonModel { + internal InternalRunStepDetailsToolCallsFileSearchObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsFileSearchObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsFileSearchObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsFileSearchObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsFileSearchObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsFileSearchObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsFileSearchObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsFileSearchObject DeserializeInternalRunStepDetailsToolCallsFileSearchObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsFileSearchObject DeserializeInternalRunStepDetailsToolCallsFileSearchObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch = default; - RunStepToolCallKind type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.RunStepToolCallKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("id"u8)) { - fileSearch = InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToRunStepToolCallKind(); + kind = prop.Value.GetString().ToRunStepToolCallKind(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("file_search"u8)) { - id = property.Value.GetString(); + fileSearch = InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsFileSearchObject(type, id, serializedAdditionalRawData, fileSearch); + return new InternalRunStepDetailsToolCallsFileSearchObject(id, kind, additionalBinaryDataProperties, fileSearch); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Wr } } - InternalRunStepDetailsToolCallsFileSearchObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsFileSearchObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsFileSearchObject)PersistableModelCreateCore(data, options); + protected override RunStepToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsFileSearchObject(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRunStepDetailsToolCallsFileSearchObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsToolCallsFileSearchObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsFileSearchObject internalRunStepDetailsToolCallsFileSearchObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsFileSearchObject(document.RootElement); + if (internalRunStepDetailsToolCallsFileSearchObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsFileSearchObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsFileSearchObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsFileSearchObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.cs index 37cade91a..3346c806c 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObject.cs @@ -9,24 +9,16 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFileSearchObject : RunStepToolCall { - internal InternalRunStepDetailsToolCallsFileSearchObject(string id, InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(id) + internal InternalRunStepDetailsToolCallsFileSearchObject(string id, InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(id, Assistants.RunStepToolCallKind.FileSearch) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(fileSearch, nameof(fileSearch)); - - Kind = RunStepToolCallKind.FileSearch; FileSearch = fileSearch; } - internal InternalRunStepDetailsToolCallsFileSearchObject(RunStepToolCallKind kind, string id, IDictionary serializedAdditionalRawData, InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(kind, id, serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsFileSearchObject(string id, Assistants.RunStepToolCallKind kind, IDictionary additionalBinaryDataProperties, InternalRunStepDetailsToolCallsFileSearchObjectFileSearch fileSearch) : base(id, kind, additionalBinaryDataProperties) { FileSearch = fileSearch; } - internal InternalRunStepDetailsToolCallsFileSearchObject() - { - } - public InternalRunStepDetailsToolCallsFileSearchObjectFileSearch FileSearch { get; } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs index 33843ea41..a19bd3e96 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,31 +15,36 @@ internal partial class InternalRunStepDetailsToolCallsFileSearchObjectFileSearch { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsFileSearchObjectFileSearch)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("ranking_options") != true && Optional.IsDefined(RankingOptions)) - { - writer.WritePropertyName("ranking_options"u8); - writer.WriteObjectValue(RankingOptions, options); - } - if (SerializedAdditionalRawData?.ContainsKey("results") != true && true && Optional.IsCollectionDefined(Results)) + if (true && Optional.IsCollectionDefined(Results) && _additionalBinaryDataProperties?.ContainsKey("results") != true) { writer.WritePropertyName("results"u8); writer.WriteStartArray(); - foreach (var item in Results) + foreach (RunStepFileSearchResult item in Results) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(RankingOptions) && _additionalBinaryDataProperties?.ContainsKey("ranking_options") != true) + { + writer.WritePropertyName("ranking_options"u8); + writer.WriteObjectValue(RankingOptions, options); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +52,7 @@ void IJsonModel.Write } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,72 +61,68 @@ void IJsonModel.Write #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsFileSearchObjectFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsFileSearchObjectFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsToolCallsFileSearchObjectFileSearch JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsFileSearchObjectFileSearch)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsFileSearchObjectFileSearch DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsFileSearchObjectFileSearch DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - FileSearchRankingOptions rankingOptions = default; IReadOnlyList results = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + FileSearchRankingOptions rankingOptions = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("ranking_options"u8)) + if (prop.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(property.Value, options); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(RunStepFileSearchResult.DeserializeRunStepFileSearchResult(item, options)); + } + results = array; continue; } - if (property.NameEquals("results"u8)) + if (prop.NameEquals("ranking_options"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(RunStepFileSearchResult.DeserializeRunStepFileSearchResult(item, options)); - } - results = array; + rankingOptions = FileSearchRankingOptions.DeserializeFileSearchRankingOptions(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsFileSearchObjectFileSearch(rankingOptions, results ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalRunStepDetailsToolCallsFileSearchObjectFileSearch(results ?? new ChangeTrackingList(), rankingOptions, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -130,15 +132,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsFileSearchObjectFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsToolCallsFileSearchObjectFileSearch 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, options); } default: @@ -148,15 +151,20 @@ InternalRunStepDetailsToolCallsFileSearchObjectFileSearch IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsToolCallsFileSearchObjectFileSearch FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsFileSearchObjectFileSearch internalRunStepDetailsToolCallsFileSearchObjectFileSearch) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement); + if (internalRunStepDetailsToolCallsFileSearchObjectFileSearch == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsFileSearchObjectFileSearch, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsFileSearchObjectFileSearch(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsFileSearchObjectFileSearch(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.cs index e48b1ce80..2052d81a0 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchObjectFileSearch.cs @@ -4,23 +4,32 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFileSearchObjectFileSearch { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsToolCallsFileSearchObjectFileSearch() { Results = new ChangeTrackingList(); } - internal InternalRunStepDetailsToolCallsFileSearchObjectFileSearch(FileSearchRankingOptions rankingOptions, IReadOnlyList results, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsFileSearchObjectFileSearch(IReadOnlyList results, FileSearchRankingOptions rankingOptions, IDictionary additionalBinaryDataProperties) { - RankingOptions = rankingOptions; Results = results; - SerializedAdditionalRawData = serializedAdditionalRawData; + RankingOptions = rankingOptions; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public IReadOnlyList Results { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.Serialization.cs index 2d2fa16ef..abb3aecef 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject : IJsonModel { + internal InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("ranker") != true) + if (_additionalBinaryDataProperties?.ContainsKey("ranker") != true) { writer.WritePropertyName("ranker"u8); writer.WriteStringValue(Ranker.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("score_threshold") != true) + if (_additionalBinaryDataProperties?.ContainsKey("score_threshold") != true) { writer.WritePropertyName("score_threshold"u8); writer.WriteNumberValue(ScoreThreshold); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.W } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.W #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker ranker = default; float scoreThreshold = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("ranker"u8)) + if (prop.NameEquals("ranker"u8)) { - ranker = new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(property.Value.GetString()); + ranker = new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(prop.Value.GetString()); continue; } - if (property.NameEquals("score_threshold"u8)) + if (prop.NameEquals("score_threshold"u8)) { - scoreThreshold = property.Value.GetSingle(); + scoreThreshold = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(ranker, scoreThreshold, serializedAdditionalRawData); + return new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(ranker, scoreThreshold, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject IPersistableModel< string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject internalRunStepDetailsToolCallsFileSearchRankingOptionsObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(document.RootElement); + if (internalRunStepDetailsToolCallsFileSearchRankingOptionsObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsFileSearchRankingOptionsObject, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.cs index 84c5989ab..e0e24642a 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject.cs @@ -9,25 +9,28 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(float scoreThreshold) { ScoreThreshold = scoreThreshold; } - internal InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker ranker, float scoreThreshold, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker ranker, float scoreThreshold, IDictionary additionalBinaryDataProperties) { Ranker = ranker; ScoreThreshold = scoreThreshold; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker Ranker { get; } = InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker.Default20240821; + public InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker Ranker { get; } = "default_2024_08_21"; public float ScoreThreshold { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker.cs index 3e0d585cf..03d987094 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker : IEquatable { private readonly string _value; + private const string Default20240821Value = "default_2024_08_21"; public InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string Default20240821Value = "default_2024_08_21"; + _value = value; + } public static InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker Default20240821 { get; } = new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(Default20240821Value); + public static bool operator ==(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker left, InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker right) => left.Equals(right); + public static bool operator !=(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker left, InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker right) => !left.Equals(right); + public static implicit operator InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(string value) => new InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker other && Equals(other); + public bool Equals(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObjectRanker other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.Serialization.cs index 118284fa3..b2de59874 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.Serialization.cs @@ -7,113 +7,91 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFunctionObject : IJsonModel { + internal InternalRunStepDetailsToolCallsFunctionObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsFunctionObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("function") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("function") != true) { writer.WritePropertyName("function"u8); writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsFunctionObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsFunctionObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsFunctionObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsFunctionObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsFunctionObject DeserializeInternalRunStepDetailsToolCallsFunctionObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsFunctionObject DeserializeInternalRunStepDetailsToolCallsFunctionObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRunStepDetailsToolCallsFunctionObjectFunction function = default; - RunStepToolCallKind type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.RunStepToolCallKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalRunStepDetailsToolCallsFunctionObjectFunction function = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("function"u8)) + if (prop.NameEquals("id"u8)) { - function = InternalRunStepDetailsToolCallsFunctionObjectFunction.DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(property.Value, options); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToRunStepToolCallKind(); + kind = prop.Value.GetString().ToRunStepToolCallKind(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("function"u8)) { - id = property.Value.GetString(); + function = InternalRunStepDetailsToolCallsFunctionObjectFunction.DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsFunctionObject(type, id, serializedAdditionalRawData, function); + return new InternalRunStepDetailsToolCallsFunctionObject(id, kind, additionalBinaryDataProperties, function); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +101,16 @@ BinaryData IPersistableModel.Writ } } - InternalRunStepDetailsToolCallsFunctionObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsFunctionObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsFunctionObject)PersistableModelCreateCore(data, options); + protected override RunStepToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsFunctionObject(document.RootElement, options); } default: @@ -141,15 +120,20 @@ InternalRunStepDetailsToolCallsFunctionObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsToolCallsFunctionObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsFunctionObject internalRunStepDetailsToolCallsFunctionObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsFunctionObject(document.RootElement); + if (internalRunStepDetailsToolCallsFunctionObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsFunctionObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsFunctionObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsFunctionObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.cs index 22ae0b221..a6c864fee 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObject.cs @@ -9,24 +9,16 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFunctionObject : RunStepToolCall { - internal InternalRunStepDetailsToolCallsFunctionObject(string id, InternalRunStepDetailsToolCallsFunctionObjectFunction function) : base(id) + internal InternalRunStepDetailsToolCallsFunctionObject(string id, InternalRunStepDetailsToolCallsFunctionObjectFunction function) : base(id, Assistants.RunStepToolCallKind.Function) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(function, nameof(function)); - - Kind = RunStepToolCallKind.Function; Function = function; } - internal InternalRunStepDetailsToolCallsFunctionObject(RunStepToolCallKind kind, string id, IDictionary serializedAdditionalRawData, InternalRunStepDetailsToolCallsFunctionObjectFunction function) : base(kind, id, serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsFunctionObject(string id, Assistants.RunStepToolCallKind kind, IDictionary additionalBinaryDataProperties, InternalRunStepDetailsToolCallsFunctionObjectFunction function) : base(id, kind, additionalBinaryDataProperties) { Function = function; } - internal InternalRunStepDetailsToolCallsFunctionObject() - { - } - public InternalRunStepDetailsToolCallsFunctionObjectFunction Function { get; } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.Serialization.cs index d72f701a2..ae3bbe299 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.Serialization.cs @@ -7,31 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFunctionObjectFunction : IJsonModel { + internal InternalRunStepDetailsToolCallsFunctionObjectFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsFunctionObjectFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData?.ContainsKey("output") != true) + if (_additionalBinaryDataProperties?.ContainsKey("output") != true) { if (Output != null) { @@ -40,12 +50,12 @@ void IJsonModel.Write(Utf } else { - writer.WriteNull("output"); + writer.WriteNull("output"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,25 +72,23 @@ void IJsonModel.Write(Utf #endif } } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsFunctionObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunStepDetailsToolCallsFunctionObjectFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsFunctionObjectFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsFunctionObjectFunction DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsFunctionObjectFunction DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -88,44 +96,42 @@ internal static InternalRunStepDetailsToolCallsFunctionObjectFunction Deserializ string name = default; string arguments = default; string output = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - arguments = property.Value.GetString(); + arguments = prop.Value.GetString(); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("output"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { output = null; continue; } - output = property.Value.GetString(); + output = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsFunctionObjectFunction(name, arguments, output, serializedAdditionalRawData); + return new InternalRunStepDetailsToolCallsFunctionObjectFunction(name, arguments, output, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +141,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsFunctionObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunStepDetailsToolCallsFunctionObjectFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(document.RootElement, options); } default: @@ -153,15 +160,20 @@ InternalRunStepDetailsToolCallsFunctionObjectFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunStepDetailsToolCallsFunctionObjectFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsFunctionObjectFunction internalRunStepDetailsToolCallsFunctionObjectFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(document.RootElement); + if (internalRunStepDetailsToolCallsFunctionObjectFunction == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsFunctionObjectFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsFunctionObjectFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsFunctionObjectFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.cs index 588377cde..74a5a26dc 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsFunctionObjectFunction.cs @@ -9,31 +9,33 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsFunctionObjectFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunStepDetailsToolCallsFunctionObjectFunction(string name, string arguments, string output) { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(arguments, nameof(arguments)); - Name = name; Arguments = arguments; Output = output; } - internal InternalRunStepDetailsToolCallsFunctionObjectFunction(string name, string arguments, string output, IDictionary serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsFunctionObjectFunction(string name, string arguments, string output, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; Output = output; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRunStepDetailsToolCallsFunctionObjectFunction() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; } + public string Arguments { get; } + public string Output { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsObject.Serialization.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsObject.Serialization.cs index 122837da8..06127716e 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsObject.Serialization.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsObject.Serialization.cs @@ -7,112 +7,95 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsObject : IJsonModel { + internal InternalRunStepDetailsToolCallsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDetailsToolCallsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_calls") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("tool_calls") != true) { writer.WritePropertyName("tool_calls"u8); writer.WriteStartArray(); - foreach (var item in InternalToolCalls) + foreach (RunStepToolCall item in InternalToolCalls) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalRunStepDetailsToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDetailsToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsObject)JsonModelCreateCore(ref reader, options); + + protected override RunStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDetailsToolCallsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDetailsToolCallsObject(document.RootElement, options); } - internal static InternalRunStepDetailsToolCallsObject DeserializeInternalRunStepDetailsToolCallsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunStepDetailsToolCallsObject DeserializeInternalRunStepDetailsToolCallsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList toolCalls = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "tool_calls"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + IReadOnlyList internalToolCalls = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_calls"u8)) + if (prop.NameEquals("type"u8)) + { + @type = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("tool_calls"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(RunStepToolCall.DeserializeRunStepToolCall(item, options)); } - toolCalls = array; - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); + internalToolCalls = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunStepDetailsToolCallsObject(type, serializedAdditionalRawData, toolCalls); + return new InternalRunStepDetailsToolCallsObject(@type, additionalBinaryDataProperties, internalToolCalls); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -122,15 +105,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalRunStepDetailsToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDetailsToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalRunStepDetailsToolCallsObject)PersistableModelCreateCore(data, options); + protected override RunStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDetailsToolCallsObject(document.RootElement, options); } default: @@ -140,15 +124,20 @@ InternalRunStepDetailsToolCallsObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalRunStepDetailsToolCallsObject FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunStepDetailsToolCallsObject internalRunStepDetailsToolCallsObject) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunStepDetailsToolCallsObject(document.RootElement); + if (internalRunStepDetailsToolCallsObject == null) + { + return null; + } + return BinaryContent.Create(internalRunStepDetailsToolCallsObject, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalRunStepDetailsToolCallsObject(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunStepDetailsToolCallsObject(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunStepDetailsToolCallsObject.cs b/src/Generated/Models/InternalRunStepDetailsToolCallsObject.cs index 5b428be16..c54f7ea86 100644 --- a/src/Generated/Models/InternalRunStepDetailsToolCallsObject.cs +++ b/src/Generated/Models/InternalRunStepDetailsToolCallsObject.cs @@ -10,21 +10,14 @@ namespace OpenAI.Assistants { internal partial class InternalRunStepDetailsToolCallsObject : RunStepDetails { - internal InternalRunStepDetailsToolCallsObject(IEnumerable internalToolCalls) + internal InternalRunStepDetailsToolCallsObject(IEnumerable internalToolCalls) : base("tool_calls") { - Argument.AssertNotNull(internalToolCalls, nameof(internalToolCalls)); - - Type = "tool_calls"; InternalToolCalls = internalToolCalls.ToList(); } - internal InternalRunStepDetailsToolCallsObject(string type, IDictionary serializedAdditionalRawData, IReadOnlyList internalToolCalls) : base(type, serializedAdditionalRawData) + internal InternalRunStepDetailsToolCallsObject(string @type, IDictionary additionalBinaryDataProperties, IReadOnlyList internalToolCalls) : base(@type, additionalBinaryDataProperties) { InternalToolCalls = internalToolCalls; } - - internal InternalRunStepDetailsToolCallsObject() - { - } } } diff --git a/src/Generated/Models/InternalRunStepObjectObject.cs b/src/Generated/Models/InternalRunStepObjectObject.cs index c587668ab..e4b8fc0cc 100644 --- a/src/Generated/Models/InternalRunStepObjectObject.cs +++ b/src/Generated/Models/InternalRunStepObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunStepObjectObject : IEquatable { private readonly string _value; + private const string ThreadRunStepValue = "thread.run.step"; public InternalRunStepObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadRunStepValue = "thread.run.step"; + _value = value; + } public static InternalRunStepObjectObject ThreadRunStep { get; } = new InternalRunStepObjectObject(ThreadRunStepValue); + public static bool operator ==(InternalRunStepObjectObject left, InternalRunStepObjectObject right) => left.Equals(right); + public static bool operator !=(InternalRunStepObjectObject left, InternalRunStepObjectObject right) => !left.Equals(right); + public static implicit operator InternalRunStepObjectObject(string value) => new InternalRunStepObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunStepObjectObject other && Equals(other); + public bool Equals(InternalRunStepObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalRunToolCallObjectFunction.Serialization.cs b/src/Generated/Models/InternalRunToolCallObjectFunction.Serialization.cs index 820fb48cc..1b944e191 100644 --- a/src/Generated/Models/InternalRunToolCallObjectFunction.Serialization.cs +++ b/src/Generated/Models/InternalRunToolCallObjectFunction.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalRunToolCallObjectFunction : IJsonModel { + internal InternalRunToolCallObjectFunction() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunToolCallObjectFunction)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true) + if (_additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); writer.WriteStringValue(Arguments); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - InternalRunToolCallObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunToolCallObjectFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalRunToolCallObjectFunction JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunToolCallObjectFunction)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunToolCallObjectFunction(document.RootElement, options); } - internal static InternalRunToolCallObjectFunction DeserializeInternalRunToolCallObjectFunction(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalRunToolCallObjectFunction DeserializeInternalRunToolCallObjectFunction(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; string arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - arguments = property.Value.GetString(); + arguments = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalRunToolCallObjectFunction(name, arguments, serializedAdditionalRawData); + return new InternalRunToolCallObjectFunction(name, arguments, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - InternalRunToolCallObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunToolCallObjectFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalRunToolCallObjectFunction 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunToolCallObjectFunction(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalRunToolCallObjectFunction IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalRunToolCallObjectFunction FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalRunToolCallObjectFunction internalRunToolCallObjectFunction) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalRunToolCallObjectFunction(document.RootElement); + if (internalRunToolCallObjectFunction == null) + { + return null; + } + return BinaryContent.Create(internalRunToolCallObjectFunction, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalRunToolCallObjectFunction(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalRunToolCallObjectFunction(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalRunToolCallObjectFunction.cs b/src/Generated/Models/InternalRunToolCallObjectFunction.cs index a9f72778e..10f58a1ff 100644 --- a/src/Generated/Models/InternalRunToolCallObjectFunction.cs +++ b/src/Generated/Models/InternalRunToolCallObjectFunction.cs @@ -9,28 +9,29 @@ namespace OpenAI.Assistants { internal partial class InternalRunToolCallObjectFunction { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalRunToolCallObjectFunction(string name, string arguments) { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(arguments, nameof(arguments)); - Name = name; Arguments = arguments; } - internal InternalRunToolCallObjectFunction(string name, string arguments, IDictionary serializedAdditionalRawData) + internal InternalRunToolCallObjectFunction(string name, string arguments, IDictionary additionalBinaryDataProperties) { Name = name; Arguments = arguments; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalRunToolCallObjectFunction() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; } + public string Arguments { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalRunToolCallObjectType.cs b/src/Generated/Models/InternalRunToolCallObjectType.cs index 55e7b1d45..f788b6996 100644 --- a/src/Generated/Models/InternalRunToolCallObjectType.cs +++ b/src/Generated/Models/InternalRunToolCallObjectType.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalRunToolCallObjectType : IEquatable { private readonly string _value; + private const string FunctionValue = "function"; public InternalRunToolCallObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string FunctionValue = "function"; + _value = value; + } public static InternalRunToolCallObjectType Function { get; } = new InternalRunToolCallObjectType(FunctionValue); + public static bool operator ==(InternalRunToolCallObjectType left, InternalRunToolCallObjectType right) => left.Equals(right); + public static bool operator !=(InternalRunToolCallObjectType left, InternalRunToolCallObjectType right) => !left.Equals(right); + public static implicit operator InternalRunToolCallObjectType(string value) => new InternalRunToolCallObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalRunToolCallObjectType other && Equals(other); + public bool Equals(InternalRunToolCallObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalStaticChunkingStrategyDetails.Serialization.cs b/src/Generated/Models/InternalStaticChunkingStrategyDetails.Serialization.cs index f40eef604..7042f12d0 100644 --- a/src/Generated/Models/InternalStaticChunkingStrategyDetails.Serialization.cs +++ b/src/Generated/Models/InternalStaticChunkingStrategyDetails.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalStaticChunkingStrategyDetails : IJsonModel { + internal InternalStaticChunkingStrategyDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalStaticChunkingStrategyDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("max_chunk_size_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("max_chunk_size_tokens") != true) { writer.WritePropertyName("max_chunk_size_tokens"u8); writer.WriteNumberValue(MaxChunkSizeTokens); } - if (SerializedAdditionalRawData?.ContainsKey("chunk_overlap_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("chunk_overlap_tokens") != true) { writer.WritePropertyName("chunk_overlap_tokens"u8); writer.WriteNumberValue(ChunkOverlapTokens); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writ } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writ #endif } } - writer.WriteEndObject(); } - InternalStaticChunkingStrategyDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalStaticChunkingStrategyDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalStaticChunkingStrategyDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalStaticChunkingStrategyDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalStaticChunkingStrategyDetails(document.RootElement, options); } - internal static InternalStaticChunkingStrategyDetails DeserializeInternalStaticChunkingStrategyDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalStaticChunkingStrategyDetails DeserializeInternalStaticChunkingStrategyDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } int maxChunkSizeTokens = default; int chunkOverlapTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("max_chunk_size_tokens"u8)) + if (prop.NameEquals("max_chunk_size_tokens"u8)) { - maxChunkSizeTokens = property.Value.GetInt32(); + maxChunkSizeTokens = prop.Value.GetInt32(); continue; } - if (property.NameEquals("chunk_overlap_tokens"u8)) + if (prop.NameEquals("chunk_overlap_tokens"u8)) { - chunkOverlapTokens = property.Value.GetInt32(); + chunkOverlapTokens = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalStaticChunkingStrategyDetails(maxChunkSizeTokens, chunkOverlapTokens, serializedAdditionalRawData); + return new InternalStaticChunkingStrategyDetails(maxChunkSizeTokens, chunkOverlapTokens, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelR } } - InternalStaticChunkingStrategyDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalStaticChunkingStrategyDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalStaticChunkingStrategyDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalStaticChunkingStrategyDetails(document.RootElement, options); } default: @@ -130,15 +137,20 @@ InternalStaticChunkingStrategyDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalStaticChunkingStrategyDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalStaticChunkingStrategyDetails internalStaticChunkingStrategyDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalStaticChunkingStrategyDetails(document.RootElement); + if (internalStaticChunkingStrategyDetails == null) + { + return null; + } + return BinaryContent.Create(internalStaticChunkingStrategyDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalStaticChunkingStrategyDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalStaticChunkingStrategyDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalStaticChunkingStrategyDetails.cs b/src/Generated/Models/InternalStaticChunkingStrategyDetails.cs index 26a6aa2e1..3a88a1f8c 100644 --- a/src/Generated/Models/InternalStaticChunkingStrategyDetails.cs +++ b/src/Generated/Models/InternalStaticChunkingStrategyDetails.cs @@ -9,25 +9,29 @@ namespace OpenAI.VectorStores { internal partial class InternalStaticChunkingStrategyDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalStaticChunkingStrategyDetails(int maxChunkSizeTokens, int chunkOverlapTokens) { MaxChunkSizeTokens = maxChunkSizeTokens; ChunkOverlapTokens = chunkOverlapTokens; } - internal InternalStaticChunkingStrategyDetails(int maxChunkSizeTokens, int chunkOverlapTokens, IDictionary serializedAdditionalRawData) + internal InternalStaticChunkingStrategyDetails(int maxChunkSizeTokens, int chunkOverlapTokens, IDictionary additionalBinaryDataProperties) { MaxChunkSizeTokens = maxChunkSizeTokens; ChunkOverlapTokens = chunkOverlapTokens; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalStaticChunkingStrategyDetails() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int MaxChunkSizeTokens { get; set; } + public int ChunkOverlapTokens { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.Serialization.cs b/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.Serialization.cs index 47c705b9e..3058302f7 100644 --- a/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.Serialization.cs +++ b/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalStaticChunkingStrategyRequestParam : IJsonModel { + internal InternalStaticChunkingStrategyRequestParam() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalStaticChunkingStrategyRequestParam)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("static") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("static") != true) { writer.WritePropertyName("static"u8); writer.WriteObjectValue(Static, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - InternalStaticChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalStaticChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalStaticChunkingStrategyRequestParam)JsonModelCreateCore(ref reader, options); + + protected override InternalFileChunkingStrategyRequestParam JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalStaticChunkingStrategyRequestParam)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalStaticChunkingStrategyRequestParam(document.RootElement, options); } - internal static InternalStaticChunkingStrategyRequestParam DeserializeInternalStaticChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalStaticChunkingStrategyRequestParam DeserializeInternalStaticChunkingStrategyRequestParam(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "static"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalStaticChunkingStrategyDetails @static = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("static"u8)) + if (prop.NameEquals("type"u8)) { - @static = InternalStaticChunkingStrategyDetails.DeserializeInternalStaticChunkingStrategyDetails(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("static"u8)) { - type = property.Value.GetString(); + @static = InternalStaticChunkingStrategyDetails.DeserializeInternalStaticChunkingStrategyDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalStaticChunkingStrategyRequestParam(type, serializedAdditionalRawData, @static); + return new InternalStaticChunkingStrategyRequestParam(@type, additionalBinaryDataProperties, @static); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(M } } - InternalStaticChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalStaticChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalStaticChunkingStrategyRequestParam)PersistableModelCreateCore(data, options); + protected override InternalFileChunkingStrategyRequestParam 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalStaticChunkingStrategyRequestParam(document.RootElement, options); } default: @@ -130,15 +114,20 @@ InternalStaticChunkingStrategyRequestParam IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalStaticChunkingStrategyRequestParam FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalStaticChunkingStrategyRequestParam internalStaticChunkingStrategyRequestParam) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalStaticChunkingStrategyRequestParam(document.RootElement); + if (internalStaticChunkingStrategyRequestParam == null) + { + return null; + } + return BinaryContent.Create(internalStaticChunkingStrategyRequestParam, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalStaticChunkingStrategyRequestParam(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalStaticChunkingStrategyRequestParam(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.cs b/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.cs index 2b96bd6ea..dae22259c 100644 --- a/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.cs +++ b/src/Generated/Models/InternalStaticChunkingStrategyRequestParam.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalStaticChunkingStrategyRequestParam : InternalFileChunkingStrategyRequestParam { - public InternalStaticChunkingStrategyRequestParam(InternalStaticChunkingStrategyDetails @static) + public InternalStaticChunkingStrategyRequestParam(InternalStaticChunkingStrategyDetails @static) : base("static") { Argument.AssertNotNull(@static, nameof(@static)); - Type = "static"; Static = @static; } - internal InternalStaticChunkingStrategyRequestParam(string type, IDictionary serializedAdditionalRawData, InternalStaticChunkingStrategyDetails @static) : base(type, serializedAdditionalRawData) + internal InternalStaticChunkingStrategyRequestParam(string @type, IDictionary additionalBinaryDataProperties, InternalStaticChunkingStrategyDetails @static) : base(@type, additionalBinaryDataProperties) { Static = @static; } - internal InternalStaticChunkingStrategyRequestParam() - { - } - public InternalStaticChunkingStrategyDetails Static { get; } } } diff --git a/src/Generated/Models/InternalSubmitToolOutputsRunRequest.Serialization.cs b/src/Generated/Models/InternalSubmitToolOutputsRunRequest.Serialization.cs index d6c8b0d3f..d2ffcbe89 100644 --- a/src/Generated/Models/InternalSubmitToolOutputsRunRequest.Serialization.cs +++ b/src/Generated/Models/InternalSubmitToolOutputsRunRequest.Serialization.cs @@ -7,31 +7,41 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalSubmitToolOutputsRunRequest : IJsonModel { + internal InternalSubmitToolOutputsRunRequest() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalSubmitToolOutputsRunRequest)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_outputs") != true) + if (_additionalBinaryDataProperties?.ContainsKey("tool_outputs") != true) { writer.WritePropertyName("tool_outputs"u8); writer.WriteStartArray(); - foreach (var item in ToolOutputs) + foreach (ToolOutput item in ToolOutputs) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("stream") != true && Optional.IsDefined(Stream)) + if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true) { if (Stream != null) { @@ -40,12 +50,12 @@ void IJsonModel.Write(Utf8JsonWriter writer } else { - writer.WriteNull("stream"); + writer.WriteNull("stream"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf8JsonWriter writer } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,69 +72,65 @@ void IJsonModel.Write(Utf8JsonWriter writer #endif } } - writer.WriteEndObject(); } - InternalSubmitToolOutputsRunRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalSubmitToolOutputsRunRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalSubmitToolOutputsRunRequest JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalSubmitToolOutputsRunRequest)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalSubmitToolOutputsRunRequest(document.RootElement, options); } - internal static InternalSubmitToolOutputsRunRequest DeserializeInternalSubmitToolOutputsRunRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalSubmitToolOutputsRunRequest DeserializeInternalSubmitToolOutputsRunRequest(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList toolOutputs = default; bool? stream = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_outputs"u8)) + if (prop.NameEquals("tool_outputs"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ToolOutput.DeserializeToolOutput(item, options)); } toolOutputs = array; continue; } - if (property.NameEquals("stream"u8)) + if (prop.NameEquals("stream"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { stream = null; continue; } - stream = property.Value.GetBoolean(); + stream = prop.Value.GetBoolean(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalSubmitToolOutputsRunRequest(toolOutputs, stream, serializedAdditionalRawData); + return new InternalSubmitToolOutputsRunRequest(toolOutputs, stream, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelRea } } - InternalSubmitToolOutputsRunRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalSubmitToolOutputsRunRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalSubmitToolOutputsRunRequest 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalSubmitToolOutputsRunRequest(document.RootElement, options); } default: @@ -152,15 +159,20 @@ InternalSubmitToolOutputsRunRequest IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalSubmitToolOutputsRunRequest FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalSubmitToolOutputsRunRequest internalSubmitToolOutputsRunRequest) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalSubmitToolOutputsRunRequest(document.RootElement); + if (internalSubmitToolOutputsRunRequest == null) + { + return null; + } + return BinaryContent.Create(internalSubmitToolOutputsRunRequest, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalSubmitToolOutputsRunRequest(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalSubmitToolOutputsRunRequest(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalSubmitToolOutputsRunRequest.cs b/src/Generated/Models/InternalSubmitToolOutputsRunRequest.cs index 13a442914..d009edf76 100644 --- a/src/Generated/Models/InternalSubmitToolOutputsRunRequest.cs +++ b/src/Generated/Models/InternalSubmitToolOutputsRunRequest.cs @@ -5,12 +5,14 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalSubmitToolOutputsRunRequest { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalSubmitToolOutputsRunRequest(IEnumerable toolOutputs) { Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); @@ -18,18 +20,21 @@ public InternalSubmitToolOutputsRunRequest(IEnumerable toolOutputs) ToolOutputs = toolOutputs.ToList(); } - internal InternalSubmitToolOutputsRunRequest(IList toolOutputs, bool? stream, IDictionary serializedAdditionalRawData) + internal InternalSubmitToolOutputsRunRequest(IList toolOutputs, bool? stream, IDictionary additionalBinaryDataProperties) { ToolOutputs = toolOutputs; Stream = stream; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalSubmitToolOutputsRunRequest() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList ToolOutputs { get; } + public bool? Stream { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalThreadObjectObject.cs b/src/Generated/Models/InternalThreadObjectObject.cs index 1ae268486..edef44eec 100644 --- a/src/Generated/Models/InternalThreadObjectObject.cs +++ b/src/Generated/Models/InternalThreadObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalThreadObjectObject : IEquatable { private readonly string _value; + private const string ThreadValue = "thread"; public InternalThreadObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ThreadValue = "thread"; + _value = value; + } public static InternalThreadObjectObject Thread { get; } = new InternalThreadObjectObject(ThreadValue); + public static bool operator ==(InternalThreadObjectObject left, InternalThreadObjectObject right) => left.Equals(right); + public static bool operator !=(InternalThreadObjectObject left, InternalThreadObjectObject right) => !left.Equals(right); + public static implicit operator InternalThreadObjectObject(string value) => new InternalThreadObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalThreadObjectObject other && Equals(other); + public bool Equals(InternalThreadObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalThreadObjectToolResources.Serialization.cs b/src/Generated/Models/InternalThreadObjectToolResources.Serialization.cs index d33c9da5a..131a2dc59 100644 --- a/src/Generated/Models/InternalThreadObjectToolResources.Serialization.cs +++ b/src/Generated/Models/InternalThreadObjectToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ internal partial class InternalThreadObjectToolResources : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalThreadObjectToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); writer.WriteObjectValue(FileSearch, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - InternalThreadObjectToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalThreadObjectToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalThreadObjectToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalThreadObjectToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalThreadObjectToolResources(document.RootElement, options); } - internal static InternalThreadObjectToolResources DeserializeInternalThreadObjectToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalThreadObjectToolResources DeserializeInternalThreadObjectToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalThreadObjectToolResourcesCodeInterpreter codeInterpreter = default; InternalThreadObjectToolResourcesFileSearch fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = InternalThreadObjectToolResourcesCodeInterpreter.DeserializeInternalThreadObjectToolResourcesCodeInterpreter(property.Value, options); + codeInterpreter = InternalThreadObjectToolResourcesCodeInterpreter.DeserializeInternalThreadObjectToolResourcesCodeInterpreter(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = InternalThreadObjectToolResourcesFileSearch.DeserializeInternalThreadObjectToolResourcesFileSearch(property.Value, options); + fileSearch = InternalThreadObjectToolResourcesFileSearch.DeserializeInternalThreadObjectToolResourcesFileSearch(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalThreadObjectToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new InternalThreadObjectToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write(ModelReade } } - InternalThreadObjectToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalThreadObjectToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalThreadObjectToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalThreadObjectToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ InternalThreadObjectToolResources IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalThreadObjectToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalThreadObjectToolResources internalThreadObjectToolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalThreadObjectToolResources(document.RootElement); + if (internalThreadObjectToolResources == null) + { + return null; + } + return BinaryContent.Create(internalThreadObjectToolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalThreadObjectToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalThreadObjectToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalThreadObjectToolResources.cs b/src/Generated/Models/InternalThreadObjectToolResources.cs index 5d766bb62..b7e4c296f 100644 --- a/src/Generated/Models/InternalThreadObjectToolResources.cs +++ b/src/Generated/Models/InternalThreadObjectToolResources.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { internal partial class InternalThreadObjectToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalThreadObjectToolResources() { } - internal InternalThreadObjectToolResources(InternalThreadObjectToolResourcesCodeInterpreter codeInterpreter, InternalThreadObjectToolResourcesFileSearch fileSearch, IDictionary serializedAdditionalRawData) + internal InternalThreadObjectToolResources(InternalThreadObjectToolResourcesCodeInterpreter codeInterpreter, InternalThreadObjectToolResourcesFileSearch fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public InternalThreadObjectToolResourcesCodeInterpreter CodeInterpreter { get; } + public InternalThreadObjectToolResourcesFileSearch FileSearch { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.Serialization.cs b/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.Serialization.cs index a65e19205..0b41a7f14 100644 --- a/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.Serialization.cs +++ b/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalThreadObjectToolResourcesCodeInterpreter : IJsonM { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalThreadObjectToolResourcesCodeInterpreter)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(Utf8Json } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(Utf8Json #endif } } - writer.WriteEndObject(); } - InternalThreadObjectToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalThreadObjectToolResourcesCodeInterpreter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalThreadObjectToolResourcesCodeInterpreter JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalThreadObjectToolResourcesCodeInterpreter)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalThreadObjectToolResourcesCodeInterpreter(document.RootElement, options); } - internal static InternalThreadObjectToolResourcesCodeInterpreter DeserializeInternalThreadObjectToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalThreadObjectToolResourcesCodeInterpreter DeserializeInternalThreadObjectToolResourcesCodeInterpreter(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList fileIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList fileIds = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalThreadObjectToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalThreadObjectToolResourcesCodeInterpreter(fileIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.W } } - InternalThreadObjectToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalThreadObjectToolResourcesCodeInterpreter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalThreadObjectToolResourcesCodeInterpreter 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalThreadObjectToolResourcesCodeInterpreter(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalThreadObjectToolResourcesCodeInterpreter IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalThreadObjectToolResourcesCodeInterpreter FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalThreadObjectToolResourcesCodeInterpreter internalThreadObjectToolResourcesCodeInterpreter) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalThreadObjectToolResourcesCodeInterpreter(document.RootElement); + if (internalThreadObjectToolResourcesCodeInterpreter == null) + { + return null; + } + return BinaryContent.Create(internalThreadObjectToolResourcesCodeInterpreter, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalThreadObjectToolResourcesCodeInterpreter(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalThreadObjectToolResourcesCodeInterpreter(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.cs b/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.cs index ddcfa61ee..d83af6916 100644 --- a/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.cs +++ b/src/Generated/Models/InternalThreadObjectToolResourcesCodeInterpreter.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalThreadObjectToolResourcesCodeInterpreter { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalThreadObjectToolResourcesCodeInterpreter() { FileIds = new ChangeTrackingList(); } - internal InternalThreadObjectToolResourcesCodeInterpreter(IReadOnlyList fileIds, IDictionary serializedAdditionalRawData) + internal InternalThreadObjectToolResourcesCodeInterpreter(IList fileIds, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public IReadOnlyList FileIds { get; } + public IList FileIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.Serialization.cs b/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.Serialization.cs index f2697edf2..582798a12 100644 --- a/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.Serialization.cs +++ b/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalThreadObjectToolResourcesFileSearch : IJsonModel< { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalThreadObjectToolResourcesFileSearch)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) + if (Optional.IsCollectionDefined(VectorStoreIds) && _additionalBinaryDataProperties?.ContainsKey("vector_store_ids") != true) { writer.WritePropertyName("vector_store_ids"u8); writer.WriteStartArray(); - foreach (var item in VectorStoreIds) + foreach (string item in VectorStoreIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(Utf8JsonWrite #endif } } - writer.WriteEndObject(); } - InternalThreadObjectToolResourcesFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalThreadObjectToolResourcesFileSearch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalThreadObjectToolResourcesFileSearch JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalThreadObjectToolResourcesFileSearch)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalThreadObjectToolResourcesFileSearch(document.RootElement, options); } - internal static InternalThreadObjectToolResourcesFileSearch DeserializeInternalThreadObjectToolResourcesFileSearch(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalThreadObjectToolResourcesFileSearch DeserializeInternalThreadObjectToolResourcesFileSearch(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IReadOnlyList vectorStoreIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IList vectorStoreIds = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("vector_store_ids"u8)) + if (prop.NameEquals("vector_store_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } vectorStoreIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalThreadObjectToolResourcesFileSearch(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalThreadObjectToolResourcesFileSearch(vectorStoreIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Write( } } - InternalThreadObjectToolResourcesFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalThreadObjectToolResourcesFileSearch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalThreadObjectToolResourcesFileSearch 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalThreadObjectToolResourcesFileSearch(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalThreadObjectToolResourcesFileSearch IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalThreadObjectToolResourcesFileSearch FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalThreadObjectToolResourcesFileSearch internalThreadObjectToolResourcesFileSearch) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalThreadObjectToolResourcesFileSearch(document.RootElement); + if (internalThreadObjectToolResourcesFileSearch == null) + { + return null; + } + return BinaryContent.Create(internalThreadObjectToolResourcesFileSearch, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalThreadObjectToolResourcesFileSearch(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalThreadObjectToolResourcesFileSearch(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.cs b/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.cs index 4214562af..6bcad4a1f 100644 --- a/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.cs +++ b/src/Generated/Models/InternalThreadObjectToolResourcesFileSearch.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalThreadObjectToolResourcesFileSearch { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalThreadObjectToolResourcesFileSearch() { VectorStoreIds = new ChangeTrackingList(); } - internal InternalThreadObjectToolResourcesFileSearch(IReadOnlyList vectorStoreIds, IDictionary serializedAdditionalRawData) + internal InternalThreadObjectToolResourcesFileSearch(IList vectorStoreIds, IDictionary additionalBinaryDataProperties) { VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - public IReadOnlyList VectorStoreIds { get; } + public IList VectorStoreIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs b/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs index 3b188f3b2..a01186ecb 100644 --- a/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs +++ b/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,36 @@ internal partial class InternalToolResourcesFileSearchIdsOnly : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalToolResourcesFileSearchIdsOnly)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("vector_store_ids") != true && Optional.IsCollectionDefined(VectorStoreIds)) + if (Optional.IsCollectionDefined(VectorStoreIds) && _additionalBinaryDataProperties?.ContainsKey("vector_store_ids") != true) { writer.WritePropertyName("vector_store_ids"u8); writer.WriteStartArray(); - foreach (var item in VectorStoreIds) + foreach (string item in VectorStoreIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +52,7 @@ void IJsonModel.Write(Utf8JsonWriter wri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,62 +61,65 @@ void IJsonModel.Write(Utf8JsonWriter wri #endif } } - writer.WriteEndObject(); } - InternalToolResourcesFileSearchIdsOnly IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalToolResourcesFileSearchIdsOnly IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalToolResourcesFileSearchIdsOnly JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalToolResourcesFileSearchIdsOnly)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement, options); } - internal static InternalToolResourcesFileSearchIdsOnly DeserializeInternalToolResourcesFileSearchIdsOnly(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalToolResourcesFileSearchIdsOnly DeserializeInternalToolResourcesFileSearchIdsOnly(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList vectorStoreIds = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("vector_store_ids"u8)) + if (prop.NameEquals("vector_store_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } vectorStoreIds = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalToolResourcesFileSearchIdsOnly(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new InternalToolResourcesFileSearchIdsOnly(vectorStoreIds ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -115,15 +129,16 @@ BinaryData IPersistableModel.Write(Model } } - InternalToolResourcesFileSearchIdsOnly IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalToolResourcesFileSearchIdsOnly IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalToolResourcesFileSearchIdsOnly 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement, options); } default: @@ -133,15 +148,20 @@ InternalToolResourcesFileSearchIdsOnly IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalToolResourcesFileSearchIdsOnly FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalToolResourcesFileSearchIdsOnly internalToolResourcesFileSearchIdsOnly) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement); + if (internalToolResourcesFileSearchIdsOnly == null) + { + return null; + } + return BinaryContent.Create(internalToolResourcesFileSearchIdsOnly, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalToolResourcesFileSearchIdsOnly(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalToolResourcesFileSearchIdsOnly(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs b/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs index 33ed0185e..fe7066d59 100644 --- a/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs +++ b/src/Generated/Models/InternalToolResourcesFileSearchIdsOnly.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalToolResourcesFileSearchIdsOnly { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public InternalToolResourcesFileSearchIdsOnly() { VectorStoreIds = new ChangeTrackingList(); } - internal InternalToolResourcesFileSearchIdsOnly(IList vectorStoreIds, IDictionary serializedAdditionalRawData) + internal InternalToolResourcesFileSearchIdsOnly(IList vectorStoreIds, IDictionary additionalBinaryDataProperties) { VectorStoreIds = vectorStoreIds; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList VectorStoreIds { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalTruncationObjectType.cs b/src/Generated/Models/InternalTruncationObjectType.cs index a6a78832e..284073991 100644 --- a/src/Generated/Models/InternalTruncationObjectType.cs +++ b/src/Generated/Models/InternalTruncationObjectType.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { internal readonly partial struct InternalTruncationObjectType : IEquatable { private readonly string _value; + private const string AutoValue = "auto"; + private const string LastMessagesValue = "last_messages"; public InternalTruncationObjectType(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string AutoValue = "auto"; - private const string LastMessagesValue = "last_messages"; + _value = value; + } public static InternalTruncationObjectType Auto { get; } = new InternalTruncationObjectType(AutoValue); + public static InternalTruncationObjectType LastMessages { get; } = new InternalTruncationObjectType(LastMessagesValue); + public static bool operator ==(InternalTruncationObjectType left, InternalTruncationObjectType right) => left.Equals(right); + public static bool operator !=(InternalTruncationObjectType left, InternalTruncationObjectType right) => !left.Equals(right); + public static implicit operator InternalTruncationObjectType(string value) => new InternalTruncationObjectType(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalTruncationObjectType other && Equals(other); + public bool Equals(InternalTruncationObjectType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs b/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs index ff9e4c05e..e70f6e95d 100644 --- a/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs +++ b/src/Generated/Models/InternalUnknownAssistantResponseFormat.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class InternalUnknownAssistantResponseFormat : IJsonModel { + internal InternalUnknownAssistantResponseFormat() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(AssistantResponseFormat)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - AssistantResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override AssistantResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAssistantResponseFormat(document.RootElement, options); + return AssistantResponseFormat.DeserializeAssistantResponseFormat(document.RootElement, options); } - internal static InternalUnknownAssistantResponseFormat DeserializeInternalUnknownAssistantResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownAssistantResponseFormat DeserializeInternalUnknownAssistantResponseFormat(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownAssistantResponseFormat(type, serializedAdditionalRawData); + return new InternalUnknownAssistantResponseFormat(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,16 +83,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + AssistantResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override AssistantResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeAssistantResponseFormat(document.RootElement, options); + return AssistantResponseFormat.DeserializeAssistantResponseFormat(document.RootElement, options); } default: throw new FormatException($"The model {nameof(AssistantResponseFormat)} does not support reading '{options.Format}' format."); diff --git a/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs b/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs index 13ee16c7d..ba9acc69d 100644 --- a/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs +++ b/src/Generated/Models/InternalUnknownAssistantResponseFormat.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class InternalUnknownAssistantResponseFormat : AssistantResponseFormat { - internal InternalUnknownAssistantResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal InternalUnknownAssistantResponseFormat() + internal InternalUnknownAssistantResponseFormat(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownChatMessage.Serialization.cs b/src/Generated/Models/InternalUnknownChatMessage.Serialization.cs index d0dd0537f..1dbb31bef 100644 --- a/src/Generated/Models/InternalUnknownChatMessage.Serialization.cs +++ b/src/Generated/Models/InternalUnknownChatMessage.Serialization.cs @@ -3,66 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalUnknownChatMessage : IJsonModel { - ChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalUnknownChatMessage() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(ChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessage)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + + ChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + 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(ChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatMessage(document.RootElement, options); } - internal static InternalUnknownChatMessage DeserializeInternalUnknownChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownChatMessage DeserializeInternalUnknownChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) + if (prop.NameEquals("role"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("content"u8)) { - DeserializeContentValue(property, ref content); + DeserializeContentValue(prop, ref content); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. - return new InternalUnknownChatMessage(role, content ?? new ChatMessageContent(), serializedAdditionalRawData); + return new InternalUnknownChatMessage(role, content ?? new ChatMessageContent(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -72,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options } } - ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatMessage(document.RootElement, options); } default: @@ -89,16 +101,5 @@ ChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWr } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new InternalUnknownChatMessage FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownChatMessage(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/InternalUnknownChatMessage.cs b/src/Generated/Models/InternalUnknownChatMessage.cs index 22ec97734..994ab4d56 100644 --- a/src/Generated/Models/InternalUnknownChatMessage.cs +++ b/src/Generated/Models/InternalUnknownChatMessage.cs @@ -9,11 +9,7 @@ namespace OpenAI.Chat { internal partial class InternalUnknownChatMessage : ChatMessage { - internal InternalUnknownChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData) : base(role, content, serializedAdditionalRawData) - { - } - - internal InternalUnknownChatMessage() + internal InternalUnknownChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties) : base(role, content, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs b/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs index 756d520b6..02fc947f9 100644 --- a/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs +++ b/src/Generated/Models/InternalUnknownChatResponseFormat.Serialization.cs @@ -3,59 +3,70 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { internal partial class InternalUnknownChatResponseFormat : IJsonModel { - ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal InternalUnknownChatResponseFormat() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(ChatResponseFormat)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatResponseFormat)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + + ChatResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected override ChatResponseFormat 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(ChatResponseFormat)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeChatResponseFormat(document.RootElement, options); } - internal static InternalUnknownChatResponseFormat DeserializeInternalUnknownChatResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownChatResponseFormat DeserializeInternalUnknownChatResponseFormat(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownChatResponseFormat(type, serializedAdditionalRawData); + return new InternalUnknownChatResponseFormat(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -65,15 +76,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ChatResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ChatResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeChatResponseFormat(document.RootElement, options); } default: @@ -82,16 +94,5 @@ ChatResponseFormat IPersistableModel.Create(BinaryData data, } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new InternalUnknownChatResponseFormat FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownChatResponseFormat(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/InternalUnknownChatResponseFormat.cs b/src/Generated/Models/InternalUnknownChatResponseFormat.cs index e3def713f..3a8c419f3 100644 --- a/src/Generated/Models/InternalUnknownChatResponseFormat.cs +++ b/src/Generated/Models/InternalUnknownChatResponseFormat.cs @@ -9,11 +9,7 @@ namespace OpenAI.Chat { internal partial class InternalUnknownChatResponseFormat : ChatResponseFormat { - internal InternalUnknownChatResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal InternalUnknownChatResponseFormat() + internal InternalUnknownChatResponseFormat(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownChunkingStrategy.Serialization.cs b/src/Generated/Models/InternalUnknownChunkingStrategy.Serialization.cs index 6ac1d2f89..f1c5ccde0 100644 --- a/src/Generated/Models/InternalUnknownChunkingStrategy.Serialization.cs +++ b/src/Generated/Models/InternalUnknownChunkingStrategy.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,84 +15,62 @@ internal partial class InternalUnknownChunkingStrategy : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalUnknownChunkingStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalUnknownChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalUnknownChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalUnknownChunkingStrategy)JsonModelCreateCore(ref reader, options); + + protected override FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalUnknownChunkingStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalUnknownChunkingStrategy(document.RootElement, options); } - internal static InternalUnknownChunkingStrategy DeserializeInternalUnknownChunkingStrategy(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownChunkingStrategy DeserializeInternalUnknownChunkingStrategy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "other"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownChunkingStrategy(type, serializedAdditionalRawData); + return new InternalUnknownChunkingStrategy(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +80,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalUnknownChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalUnknownChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalUnknownChunkingStrategy)PersistableModelCreateCore(data, options); + protected override FileChunkingStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalUnknownChunkingStrategy(document.RootElement, options); } default: @@ -119,15 +99,20 @@ InternalUnknownChunkingStrategy IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new InternalUnknownChunkingStrategy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalUnknownChunkingStrategy internalUnknownChunkingStrategy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownChunkingStrategy(document.RootElement); + if (internalUnknownChunkingStrategy == null) + { + return null; + } + return BinaryContent.Create(internalUnknownChunkingStrategy, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator InternalUnknownChunkingStrategy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalUnknownChunkingStrategy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalUnknownChunkingStrategy.cs b/src/Generated/Models/InternalUnknownChunkingStrategy.cs index d9026a4d2..0a1dd5f45 100644 --- a/src/Generated/Models/InternalUnknownChunkingStrategy.cs +++ b/src/Generated/Models/InternalUnknownChunkingStrategy.cs @@ -9,12 +9,11 @@ namespace OpenAI.VectorStores { internal partial class InternalUnknownChunkingStrategy : FileChunkingStrategy { - public InternalUnknownChunkingStrategy() + public InternalUnknownChunkingStrategy() : base("other") { - Type = "other"; } - internal InternalUnknownChunkingStrategy(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + internal InternalUnknownChunkingStrategy(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.Serialization.cs b/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.Serialization.cs index 5a958dfeb..2d9e4a04e 100644 --- a/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.Serialization.cs +++ b/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalUnknownFileChunkingStrategyRequestParamProxy : IJsonModel { + internal InternalUnknownFileChunkingStrategyRequestParamProxy() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFileChunkingStrategyRequestParam)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalFileChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFileChunkingStrategyRequestParam IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalFileChunkingStrategyRequestParam JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFileChunkingStrategyRequestParam)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement, options); } - internal static InternalUnknownFileChunkingStrategyRequestParamProxy DeserializeInternalUnknownFileChunkingStrategyRequestParamProxy(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownFileChunkingStrategyRequestParamProxy DeserializeInternalUnknownFileChunkingStrategyRequestParamProxy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownFileChunkingStrategyRequestParamProxy(type, serializedAdditionalRawData); + return new InternalUnknownFileChunkingStrategyRequestParamProxy(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(Mod } } - InternalFileChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFileChunkingStrategyRequestParam IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalFileChunkingStrategyRequestParam 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFileChunkingStrategyRequestParam(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalFileChunkingStrategyRequestParam IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new InternalUnknownFileChunkingStrategyRequestParamProxy FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownFileChunkingStrategyRequestParamProxy(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.cs b/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.cs index 91f50cabb..e2067aeef 100644 --- a/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.cs +++ b/src/Generated/Models/InternalUnknownFileChunkingStrategyRequestParamProxy.cs @@ -9,11 +9,7 @@ namespace OpenAI.VectorStores { internal partial class InternalUnknownFileChunkingStrategyRequestParamProxy : InternalFileChunkingStrategyRequestParam { - internal InternalUnknownFileChunkingStrategyRequestParamProxy(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal InternalUnknownFileChunkingStrategyRequestParamProxy() + internal InternalUnknownFileChunkingStrategyRequestParamProxy(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.Serialization.cs b/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.Serialization.cs index c98a69cd1..f0b262ddf 100644 --- a/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.Serialization.cs +++ b/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalUnknownFileChunkingStrategyResponseParamProxy : IJsonModel { + internal InternalUnknownFileChunkingStrategyResponseParamProxy() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FileChunkingStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - FileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FileChunkingStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFileChunkingStrategy(document.RootElement, options); } - internal static InternalUnknownFileChunkingStrategyResponseParamProxy DeserializeInternalUnknownFileChunkingStrategyResponseParamProxy(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownFileChunkingStrategyResponseParamProxy DeserializeInternalUnknownFileChunkingStrategyResponseParamProxy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownFileChunkingStrategyResponseParamProxy(type, serializedAdditionalRawData); + return new InternalUnknownFileChunkingStrategyResponseParamProxy(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - FileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override FileChunkingStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFileChunkingStrategy(document.RootElement, options); } default: @@ -118,16 +101,5 @@ FileChunkingStrategy IPersistableModel.Create(BinaryData d } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new InternalUnknownFileChunkingStrategyResponseParamProxy FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownFileChunkingStrategyResponseParamProxy(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.cs b/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.cs index db5bbec83..46c4b12c8 100644 --- a/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.cs +++ b/src/Generated/Models/InternalUnknownFileChunkingStrategyResponseParamProxy.cs @@ -9,11 +9,7 @@ namespace OpenAI.VectorStores { internal partial class InternalUnknownFileChunkingStrategyResponseParamProxy : FileChunkingStrategy { - internal InternalUnknownFileChunkingStrategyResponseParamProxy(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal InternalUnknownFileChunkingStrategyResponseParamProxy() + internal InternalUnknownFileChunkingStrategyResponseParamProxy(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs b/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs index 43b17f909..f921f0ade 100644 --- a/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs +++ b/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { internal partial class InternalUnknownOmniTypedResponseFormat : IJsonModel { + internal InternalUnknownOmniTypedResponseFormat() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalOmniTypedResponseFormat)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalOmniTypedResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalOmniTypedResponseFormat JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalOmniTypedResponseFormat)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); } - internal static InternalUnknownOmniTypedResponseFormat DeserializeInternalUnknownOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUnknownOmniTypedResponseFormat DeserializeInternalUnknownOmniTypedResponseFormat(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownOmniTypedResponseFormat(type, serializedAdditionalRawData); + return new InternalUnknownOmniTypedResponseFormat(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalOmniTypedResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalOmniTypedResponseFormat 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalOmniTypedResponseFormat(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalOmniTypedResponseFormat IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new InternalUnknownOmniTypedResponseFormat FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownOmniTypedResponseFormat(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs b/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs index 8ae4808ff..071536a4b 100644 --- a/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs +++ b/src/Generated/Models/InternalUnknownOmniTypedResponseFormat.cs @@ -9,11 +9,7 @@ namespace OpenAI.Internal { internal partial class InternalUnknownOmniTypedResponseFormat : InternalOmniTypedResponseFormat { - internal InternalUnknownOmniTypedResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal InternalUnknownOmniTypedResponseFormat() + internal InternalUnknownOmniTypedResponseFormat(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/InternalUpload.Serialization.cs b/src/Generated/Models/InternalUpload.Serialization.cs index 8f6ce8ce8..6ed8b43a3 100644 --- a/src/Generated/Models/InternalUpload.Serialization.cs +++ b/src/Generated/Models/InternalUpload.Serialization.cs @@ -7,61 +7,71 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { internal partial class InternalUpload : IJsonModel { + internal InternalUpload() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalUpload)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("filename") != true) + if (_additionalBinaryDataProperties?.ContainsKey("filename") != true) { writer.WritePropertyName("filename"u8); writer.WriteStringValue(Filename); } - if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) + if (_additionalBinaryDataProperties?.ContainsKey("bytes") != true) { writer.WritePropertyName("bytes"u8); writer.WriteNumberValue(Bytes); } - if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + if (_additionalBinaryDataProperties?.ContainsKey("purpose") != true) { writer.WritePropertyName("purpose"u8); writer.WriteStringValue(Purpose); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("expires_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("expires_at") != true) { writer.WritePropertyName("expires_at"u8); writer.WriteNumberValue(ExpiresAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true && Optional.IsDefined(Object)) + if (Optional.IsDefined(Object) && _additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("file") != true && Optional.IsDefined(File)) + if (Optional.IsDefined(File) && _additionalBinaryDataProperties?.ContainsKey("file") != true) { if (File != null) { @@ -70,12 +80,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } else { - writer.WriteNull("file"); + writer.WriteNull("file"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -83,7 +93,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -92,25 +102,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp #endif } } - writer.WriteEndObject(); } - InternalUpload IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalUpload IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalUpload JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalUpload)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalUpload(document.RootElement, options); } - internal static InternalUpload DeserializeInternalUpload(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUpload DeserializeInternalUpload(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -123,72 +131,69 @@ internal static InternalUpload DeserializeInternalUpload(JsonElement element, Mo InternalUploadStatus status = default; DateTimeOffset expiresAt = default; InternalUploadObject? @object = default; - OpenAIFile file = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + OpenAIFile @file = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("filename"u8)) + if (prop.NameEquals("filename"u8)) { - filename = property.Value.GetString(); + filename = prop.Value.GetString(); continue; } - if (property.NameEquals("bytes"u8)) + if (prop.NameEquals("bytes"u8)) { - bytes = property.Value.GetInt32(); + bytes = prop.Value.GetInt32(); continue; } - if (property.NameEquals("purpose"u8)) + if (prop.NameEquals("purpose"u8)) { - purpose = property.Value.GetString(); + purpose = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new InternalUploadStatus(property.Value.GetString()); + status = new InternalUploadStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("expires_at"u8)) + if (prop.NameEquals("expires_at"u8)) { - expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - @object = new InternalUploadObject(property.Value.GetString()); + @object = new InternalUploadObject(prop.Value.GetString()); continue; } - if (property.NameEquals("file"u8)) + if (prop.NameEquals("file"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - file = null; + @file = null; continue; } - file = OpenAIFile.DeserializeOpenAIFile(property.Value, options); + @file = OpenAIFile.DeserializeOpenAIFile(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalUpload( id, createdAt, @@ -198,14 +203,15 @@ internal static InternalUpload DeserializeInternalUpload(JsonElement element, Mo status, expiresAt, @object, - file, - serializedAdditionalRawData); + @file, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -215,15 +221,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - InternalUpload IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalUpload IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalUpload 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalUpload(document.RootElement, options); } default: @@ -233,15 +240,20 @@ InternalUpload IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalUpload FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalUpload internalUpload) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUpload(document.RootElement); + if (internalUpload == null) + { + return null; + } + return BinaryContent.Create(internalUpload, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalUpload(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalUpload(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalUpload.cs b/src/Generated/Models/InternalUpload.cs index 8e796539d..43d97a848 100644 --- a/src/Generated/Models/InternalUpload.cs +++ b/src/Generated/Models/InternalUpload.cs @@ -9,13 +9,10 @@ namespace OpenAI.Files { internal partial class InternalUpload { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(filename, nameof(filename)); - Argument.AssertNotNull(purpose, nameof(purpose)); - Id = id; CreatedAt = createdAt; Filename = filename; @@ -25,7 +22,7 @@ internal InternalUpload(string id, DateTimeOffset createdAt, string filename, in ExpiresAt = expiresAt; } - internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt, InternalUploadObject? @object, OpenAIFile file, IDictionary serializedAdditionalRawData) + internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt, InternalUploadObject? @object, OpenAIFile @file, IDictionary additionalBinaryDataProperties) { Id = id; CreatedAt = createdAt; @@ -35,22 +32,32 @@ internal InternalUpload(string id, DateTimeOffset createdAt, string filename, in Status = status; ExpiresAt = expiresAt; Object = @object; - File = file; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalUpload() - { + File = @file; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string Filename { get; } + public int Bytes { get; } + public string Purpose { get; } + public InternalUploadStatus Status { get; } + public DateTimeOffset ExpiresAt { get; } + public InternalUploadObject? Object { get; } + public OpenAIFile File { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalUploadObject.cs b/src/Generated/Models/InternalUploadObject.cs index 9dacd622a..db22cc690 100644 --- a/src/Generated/Models/InternalUploadObject.cs +++ b/src/Generated/Models/InternalUploadObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalUploadObject : IEquatable { private readonly string _value; + private const string UploadValue = "upload"; public InternalUploadObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UploadValue = "upload"; + _value = value; + } public static InternalUploadObject Upload { get; } = new InternalUploadObject(UploadValue); + public static bool operator ==(InternalUploadObject left, InternalUploadObject right) => left.Equals(right); + public static bool operator !=(InternalUploadObject left, InternalUploadObject right) => !left.Equals(right); + public static implicit operator InternalUploadObject(string value) => new InternalUploadObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalUploadObject other && Equals(other); + public bool Equals(InternalUploadObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalUploadPart.Serialization.cs b/src/Generated/Models/InternalUploadPart.Serialization.cs index c6f4c77f8..d50ead99d 100644 --- a/src/Generated/Models/InternalUploadPart.Serialization.cs +++ b/src/Generated/Models/InternalUploadPart.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { internal partial class InternalUploadPart : IJsonModel { + internal InternalUploadPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalUploadPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("upload_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("upload_id") != true) { writer.WritePropertyName("upload_id"u8); writer.WriteStringValue(UploadId); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); writer.WriteStringValue(Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,25 +70,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - InternalUploadPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalUploadPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalUploadPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalUploadPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalUploadPart(document.RootElement, options); } - internal static InternalUploadPart DeserializeInternalUploadPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalUploadPart DeserializeInternalUploadPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -87,44 +95,42 @@ internal static InternalUploadPart DeserializeInternalUploadPart(JsonElement ele DateTimeOffset createdAt = default; string uploadId = default; InternalUploadPartObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("upload_id"u8)) + if (prop.NameEquals("upload_id"u8)) { - uploadId = property.Value.GetString(); + uploadId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalUploadPartObject(property.Value.GetString()); + @object = new InternalUploadPartObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUploadPart(id, createdAt, uploadId, @object, serializedAdditionalRawData); + return new InternalUploadPart(id, createdAt, uploadId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - InternalUploadPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalUploadPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalUploadPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalUploadPart(document.RootElement, options); } default: @@ -152,15 +159,20 @@ InternalUploadPart IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalUploadPart FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalUploadPart internalUploadPart) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUploadPart(document.RootElement); + if (internalUploadPart == null) + { + return null; + } + return BinaryContent.Create(internalUploadPart, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalUploadPart(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalUploadPart(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalUploadPart.cs b/src/Generated/Models/InternalUploadPart.cs index 5a7239276..691aa0696 100644 --- a/src/Generated/Models/InternalUploadPart.cs +++ b/src/Generated/Models/InternalUploadPart.cs @@ -9,33 +9,36 @@ namespace OpenAI.Files { internal partial class InternalUploadPart { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalUploadPart(string id, DateTimeOffset createdAt, string uploadId) { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(uploadId, nameof(uploadId)); - Id = id; CreatedAt = createdAt; UploadId = uploadId; } - internal InternalUploadPart(string id, DateTimeOffset createdAt, string uploadId, InternalUploadPartObject @object, IDictionary serializedAdditionalRawData) + internal InternalUploadPart(string id, DateTimeOffset createdAt, string uploadId, InternalUploadPartObject @object, IDictionary additionalBinaryDataProperties) { Id = id; CreatedAt = createdAt; UploadId = uploadId; Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalUploadPart() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string UploadId { get; } - public InternalUploadPartObject Object { get; } = InternalUploadPartObject.UploadPart; + + public InternalUploadPartObject Object { get; } = "upload.part"; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalUploadPartObject.cs b/src/Generated/Models/InternalUploadPartObject.cs index b790ad181..e452ba598 100644 --- a/src/Generated/Models/InternalUploadPartObject.cs +++ b/src/Generated/Models/InternalUploadPartObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalUploadPartObject : IEquatable { private readonly string _value; + private const string UploadPartValue = "upload.part"; public InternalUploadPartObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string UploadPartValue = "upload.part"; + _value = value; + } public static InternalUploadPartObject UploadPart { get; } = new InternalUploadPartObject(UploadPartValue); + public static bool operator ==(InternalUploadPartObject left, InternalUploadPartObject right) => left.Equals(right); + public static bool operator !=(InternalUploadPartObject left, InternalUploadPartObject right) => !left.Equals(right); + public static implicit operator InternalUploadPartObject(string value) => new InternalUploadPartObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalUploadPartObject other && Equals(other); + public bool Equals(InternalUploadPartObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalUploadStatus.cs b/src/Generated/Models/InternalUploadStatus.cs index 4ac5876d4..41cf69b1a 100644 --- a/src/Generated/Models/InternalUploadStatus.cs +++ b/src/Generated/Models/InternalUploadStatus.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Files { internal readonly partial struct InternalUploadStatus : IEquatable { private readonly string _value; - - public InternalUploadStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string PendingValue = "pending"; private const string CompletedValue = "completed"; private const string CancelledValue = "cancelled"; private const string ExpiredValue = "expired"; + public InternalUploadStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static InternalUploadStatus Pending { get; } = new InternalUploadStatus(PendingValue); + public static InternalUploadStatus Completed { get; } = new InternalUploadStatus(CompletedValue); + public static InternalUploadStatus Cancelled { get; } = new InternalUploadStatus(CancelledValue); + public static InternalUploadStatus Expired { get; } = new InternalUploadStatus(ExpiredValue); + public static bool operator ==(InternalUploadStatus left, InternalUploadStatus right) => left.Equals(right); + public static bool operator !=(InternalUploadStatus left, InternalUploadStatus right) => !left.Equals(right); + public static implicit operator InternalUploadStatus(string value) => new InternalUploadStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalUploadStatus other && Equals(other); + public bool Equals(InternalUploadStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.Serialization.cs b/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.Serialization.cs index fa75b3b88..36183986f 100644 --- a/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.Serialization.cs +++ b/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { internal partial class InternalVectorStoreFileBatchObjectFileCounts : IJsonModel { + internal InternalVectorStoreFileBatchObjectFileCounts() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalVectorStoreFileBatchObjectFileCounts)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("in_progress") != true) + if (_additionalBinaryDataProperties?.ContainsKey("in_progress") != true) { writer.WritePropertyName("in_progress"u8); writer.WriteNumberValue(InProgress); } - if (SerializedAdditionalRawData?.ContainsKey("completed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed") != true) { writer.WritePropertyName("completed"u8); writer.WriteNumberValue(Completed); } - if (SerializedAdditionalRawData?.ContainsKey("failed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("failed") != true) { writer.WritePropertyName("failed"u8); writer.WriteNumberValue(Failed); } - if (SerializedAdditionalRawData?.ContainsKey("cancelled") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cancelled") != true) { writer.WritePropertyName("cancelled"u8); writer.WriteNumberValue(Cancelled); } - if (SerializedAdditionalRawData?.ContainsKey("total") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total") != true) { writer.WritePropertyName("total"u8); writer.WriteNumberValue(Total); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,25 +75,23 @@ void IJsonModel.Write(Utf8JsonWrit #endif } } - writer.WriteEndObject(); } - InternalVectorStoreFileBatchObjectFileCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalVectorStoreFileBatchObjectFileCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual InternalVectorStoreFileBatchObjectFileCounts JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalVectorStoreFileBatchObjectFileCounts)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalVectorStoreFileBatchObjectFileCounts(document.RootElement, options); } - internal static InternalVectorStoreFileBatchObjectFileCounts DeserializeInternalVectorStoreFileBatchObjectFileCounts(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalVectorStoreFileBatchObjectFileCounts DeserializeInternalVectorStoreFileBatchObjectFileCounts(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -93,55 +101,53 @@ internal static InternalVectorStoreFileBatchObjectFileCounts DeserializeInternal int failed = default; int cancelled = default; int total = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("in_progress"u8)) + if (prop.NameEquals("in_progress"u8)) { - inProgress = property.Value.GetInt32(); + inProgress = prop.Value.GetInt32(); continue; } - if (property.NameEquals("completed"u8)) + if (prop.NameEquals("completed"u8)) { - completed = property.Value.GetInt32(); + completed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("failed"u8)) + if (prop.NameEquals("failed"u8)) { - failed = property.Value.GetInt32(); + failed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("cancelled"u8)) + if (prop.NameEquals("cancelled"u8)) { - cancelled = property.Value.GetInt32(); + cancelled = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total"u8)) + if (prop.NameEquals("total"u8)) { - total = property.Value.GetInt32(); + total = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new InternalVectorStoreFileBatchObjectFileCounts( inProgress, completed, failed, cancelled, total, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +157,16 @@ BinaryData IPersistableModel.Write } } - InternalVectorStoreFileBatchObjectFileCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalVectorStoreFileBatchObjectFileCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual InternalVectorStoreFileBatchObjectFileCounts 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalVectorStoreFileBatchObjectFileCounts(document.RootElement, options); } default: @@ -169,15 +176,20 @@ InternalVectorStoreFileBatchObjectFileCounts IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static InternalVectorStoreFileBatchObjectFileCounts FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(InternalVectorStoreFileBatchObjectFileCounts internalVectorStoreFileBatchObjectFileCounts) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalVectorStoreFileBatchObjectFileCounts(document.RootElement); + if (internalVectorStoreFileBatchObjectFileCounts == null) + { + return null; + } + return BinaryContent.Create(internalVectorStoreFileBatchObjectFileCounts, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator InternalVectorStoreFileBatchObjectFileCounts(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeInternalVectorStoreFileBatchObjectFileCounts(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.cs b/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.cs index 03849395d..691e6b467 100644 --- a/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.cs +++ b/src/Generated/Models/InternalVectorStoreFileBatchObjectFileCounts.cs @@ -9,7 +9,8 @@ namespace OpenAI.VectorStores { internal partial class InternalVectorStoreFileBatchObjectFileCounts { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal InternalVectorStoreFileBatchObjectFileCounts(int inProgress, int completed, int failed, int cancelled, int total) { InProgress = inProgress; @@ -19,24 +20,30 @@ internal InternalVectorStoreFileBatchObjectFileCounts(int inProgress, int comple Total = total; } - internal InternalVectorStoreFileBatchObjectFileCounts(int inProgress, int completed, int failed, int cancelled, int total, IDictionary serializedAdditionalRawData) + internal InternalVectorStoreFileBatchObjectFileCounts(int inProgress, int completed, int failed, int cancelled, int total, IDictionary additionalBinaryDataProperties) { InProgress = inProgress; Completed = completed; Failed = failed; Cancelled = cancelled; Total = total; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal InternalVectorStoreFileBatchObjectFileCounts() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int InProgress { get; } + public int Completed { get; } + public int Failed { get; } + public int Cancelled { get; } + public int Total { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/InternalVectorStoreFileBatchObjectObject.cs b/src/Generated/Models/InternalVectorStoreFileBatchObjectObject.cs index baa95d6a2..9e5e701c6 100644 --- a/src/Generated/Models/InternalVectorStoreFileBatchObjectObject.cs +++ b/src/Generated/Models/InternalVectorStoreFileBatchObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalVectorStoreFileBatchObjectObject : IEquatable { private readonly string _value; + private const string VectorStoreFilesBatchValue = "vector_store.files_batch"; public InternalVectorStoreFileBatchObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VectorStoreFilesBatchValue = "vector_store.files_batch"; + _value = value; + } public static InternalVectorStoreFileBatchObjectObject VectorStoreFilesBatch { get; } = new InternalVectorStoreFileBatchObjectObject(VectorStoreFilesBatchValue); + public static bool operator ==(InternalVectorStoreFileBatchObjectObject left, InternalVectorStoreFileBatchObjectObject right) => left.Equals(right); + public static bool operator !=(InternalVectorStoreFileBatchObjectObject left, InternalVectorStoreFileBatchObjectObject right) => !left.Equals(right); + public static implicit operator InternalVectorStoreFileBatchObjectObject(string value) => new InternalVectorStoreFileBatchObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalVectorStoreFileBatchObjectObject other && Equals(other); + public bool Equals(InternalVectorStoreFileBatchObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalVectorStoreFileObjectObject.cs b/src/Generated/Models/InternalVectorStoreFileObjectObject.cs index 89fbddec0..306b13005 100644 --- a/src/Generated/Models/InternalVectorStoreFileObjectObject.cs +++ b/src/Generated/Models/InternalVectorStoreFileObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalVectorStoreFileObjectObject : IEquatable { private readonly string _value; + private const string VectorStoreFileValue = "vector_store.file"; public InternalVectorStoreFileObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VectorStoreFileValue = "vector_store.file"; + _value = value; + } public static InternalVectorStoreFileObjectObject VectorStoreFile { get; } = new InternalVectorStoreFileObjectObject(VectorStoreFileValue); + public static bool operator ==(InternalVectorStoreFileObjectObject left, InternalVectorStoreFileObjectObject right) => left.Equals(right); + public static bool operator !=(InternalVectorStoreFileObjectObject left, InternalVectorStoreFileObjectObject right) => !left.Equals(right); + public static implicit operator InternalVectorStoreFileObjectObject(string value) => new InternalVectorStoreFileObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalVectorStoreFileObjectObject other && Equals(other); + public bool Equals(InternalVectorStoreFileObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/InternalVectorStoreObjectObject.cs b/src/Generated/Models/InternalVectorStoreObjectObject.cs index f65258a8c..6ba2fcd08 100644 --- a/src/Generated/Models/InternalVectorStoreObjectObject.cs +++ b/src/Generated/Models/InternalVectorStoreObjectObject.cs @@ -4,31 +4,38 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { internal readonly partial struct InternalVectorStoreObjectObject : IEquatable { private readonly string _value; + private const string VectorStoreValue = "vector_store"; public InternalVectorStoreObjectObject(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string VectorStoreValue = "vector_store"; + _value = value; + } public static InternalVectorStoreObjectObject VectorStore { get; } = new InternalVectorStoreObjectObject(VectorStoreValue); + public static bool operator ==(InternalVectorStoreObjectObject left, InternalVectorStoreObjectObject right) => left.Equals(right); + public static bool operator !=(InternalVectorStoreObjectObject left, InternalVectorStoreObjectObject right) => !left.Equals(right); + public static implicit operator InternalVectorStoreObjectObject(string value) => new InternalVectorStoreObjectObject(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is InternalVectorStoreObjectObject other && Equals(other); + public bool Equals(InternalVectorStoreObjectObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/MessageCollectionOrder.cs b/src/Generated/Models/MessageCollectionOrder.cs index 785954834..6c8a4153c 100644 --- a/src/Generated/Models/MessageCollectionOrder.cs +++ b/src/Generated/Models/MessageCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct MessageCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public MessageCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(MessageCollectionOrder left, MessageCollectionOrder right) => left.Equals(right); + public static bool operator !=(MessageCollectionOrder left, MessageCollectionOrder right) => !left.Equals(right); + public static implicit operator MessageCollectionOrder(string value) => new MessageCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is MessageCollectionOrder other && Equals(other); + public bool Equals(MessageCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/MessageContent.Serialization.cs b/src/Generated/Models/MessageContent.Serialization.cs index 8f0030793..f92ee5e27 100644 --- a/src/Generated/Models/MessageContent.Serialization.cs +++ b/src/Generated/Models/MessageContent.Serialization.cs @@ -6,27 +6,58 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { - public partial class MessageContent : IJsonModel + public abstract partial class MessageContent : IJsonModel { - MessageContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(MessageContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(MessageContent)} does not support writing '{format}' format."); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + MessageContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageContent 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(MessageContent)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeMessageContent(document.RootElement, options); + return MessageContent.DeserializeMessageContent(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +67,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - MessageContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeMessageContent(document.RootElement, options); + return MessageContent.DeserializeMessageContent(document.RootElement, options); } default: throw new FormatException($"The model {nameof(MessageContent)} does not support reading '{options.Format}' format."); @@ -54,15 +86,20 @@ MessageContent IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageContent messageContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageContent(document.RootElement); + if (messageContent == null) + { + return null; + } + return BinaryContent.Create(messageContent, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return MessageContent.DeserializeMessageContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageContent.cs b/src/Generated/Models/MessageContent.cs index cee79aaec..28ad462fb 100644 --- a/src/Generated/Models/MessageContent.cs +++ b/src/Generated/Models/MessageContent.cs @@ -9,11 +9,17 @@ namespace OpenAI.Assistants { public abstract partial class MessageContent { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal MessageContent(IDictionary serializedAdditionalRawData) + internal MessageContent(IDictionary additionalBinaryDataProperties) { - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/MessageCreationAttachment.Serialization.cs b/src/Generated/Models/MessageCreationAttachment.Serialization.cs index 8ab9a3be3..cce95c834 100644 --- a/src/Generated/Models/MessageCreationAttachment.Serialization.cs +++ b/src/Generated/Models/MessageCreationAttachment.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class MessageCreationAttachment : IJsonModel { + internal MessageCreationAttachment() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(MessageCreationAttachment)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true) + if (_additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); - SerializeTools(writer, options); + this.SerializeTools(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - MessageCreationAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageCreationAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageCreationAttachment JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(MessageCreationAttachment)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeMessageCreationAttachment(document.RootElement, options); } - internal static MessageCreationAttachment DeserializeMessageCreationAttachment(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageCreationAttachment DeserializeMessageCreationAttachment(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string fileId = default; IReadOnlyList tools = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { - DeserializeTools(property, ref tools); + DeserializeTools(prop, ref tools); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new MessageCreationAttachment(fileId, tools, serializedAdditionalRawData); + return new MessageCreationAttachment(fileId, tools, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - MessageCreationAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageCreationAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageCreationAttachment 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeMessageCreationAttachment(document.RootElement, options); } default: @@ -130,15 +137,20 @@ MessageCreationAttachment IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageCreationAttachment FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageCreationAttachment messageCreationAttachment) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageCreationAttachment(document.RootElement); + if (messageCreationAttachment == null) + { + return null; + } + return BinaryContent.Create(messageCreationAttachment, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageCreationAttachment(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeMessageCreationAttachment(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageCreationAttachment.cs b/src/Generated/Models/MessageCreationAttachment.cs index 3def69b58..7c9a2606c 100644 --- a/src/Generated/Models/MessageCreationAttachment.cs +++ b/src/Generated/Models/MessageCreationAttachment.cs @@ -5,12 +5,14 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.Assistants { public partial class MessageCreationAttachment { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public MessageCreationAttachment(string fileId, IEnumerable tools) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -20,17 +22,19 @@ public MessageCreationAttachment(string fileId, IEnumerable tool Tools = tools.ToList(); } - internal MessageCreationAttachment(string fileId, IReadOnlyList tools, IDictionary serializedAdditionalRawData) + internal MessageCreationAttachment(string fileId, IReadOnlyList tools, IDictionary additionalBinaryDataProperties) { FileId = fileId; Tools = tools; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal MessageCreationAttachment() + public string FileId { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public string FileId { get; } } } diff --git a/src/Generated/Models/MessageCreationOptions.Serialization.cs b/src/Generated/Models/MessageCreationOptions.Serialization.cs index cec07156b..171c2df2a 100644 --- a/src/Generated/Models/MessageCreationOptions.Serialization.cs +++ b/src/Generated/Models/MessageCreationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,30 +15,25 @@ public partial class MessageCreationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(MessageCreationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("content") != true) - { - writer.WritePropertyName("content"u8); - SerializeContent(writer, options); - } - if (SerializedAdditionalRawData?.ContainsKey("attachments") != true && Optional.IsCollectionDefined(Attachments)) + if (Optional.IsCollectionDefined(Attachments) && _additionalBinaryDataProperties?.ContainsKey("attachments") != true) { if (Attachments != null) { writer.WritePropertyName("attachments"u8); writer.WriteStartArray(); - foreach (var item in Attachments) + foreach (MessageCreationAttachment item in Attachments) { writer.WriteObjectValue(item, options); } @@ -45,10 +41,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } else { - writer.WriteNull("attachments"); + writer.WriteNull("attachments"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -57,18 +53,33 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToSerialString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("content") != true) + { + writer.WritePropertyName("content"u8); + this.SerializeContent(writer, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -76,7 +87,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -85,94 +96,97 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader #endif } } - writer.WriteEndObject(); } - MessageCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageCreationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(MessageCreationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeMessageCreationOptions(document.RootElement, options); } - internal static MessageCreationOptions DeserializeMessageCreationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageCreationOptions DeserializeMessageCreationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - MessageRole role = default; - IList content = default; IList attachments = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.MessageRole role = default; + IList content = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) - { - role = property.Value.GetString().ToMessageRole(); - continue; - } - if (property.NameEquals("content"u8)) - { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(MessageContent.DeserializeMessageContent(item, options)); - } - content = array; - continue; - } - if (property.NameEquals("attachments"u8)) + if (prop.NameEquals("attachments"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(MessageCreationAttachment.DeserializeMessageCreationAttachment(item, options)); } attachments = array; continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } + if (prop.NameEquals("role"u8)) + { + role = prop.Value.GetString().ToMessageRole(); + continue; + } + if (prop.NameEquals("content"u8)) + { + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(MessageContent.DeserializeMessageContent(item, options)); + } + content = array; + continue; + } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new MessageCreationOptions(role, content, attachments ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new MessageCreationOptions(attachments ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), role, content, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -182,15 +196,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - MessageCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageCreationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeMessageCreationOptions(document.RootElement, options); } default: @@ -200,15 +215,20 @@ MessageCreationOptions IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageCreationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageCreationOptions messageCreationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageCreationOptions(document.RootElement); + if (messageCreationOptions == null) + { + return null; + } + return BinaryContent.Create(messageCreationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageCreationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeMessageCreationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageCreationOptions.cs b/src/Generated/Models/MessageCreationOptions.cs index 123344624..b1399e854 100644 --- a/src/Generated/Models/MessageCreationOptions.cs +++ b/src/Generated/Models/MessageCreationOptions.cs @@ -4,23 +4,30 @@ using System; using System.Collections.Generic; -using System.Linq; namespace OpenAI.Assistants { public partial class MessageCreationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal MessageCreationOptions(MessageRole role, IList content, IList attachments, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal MessageCreationOptions(IList attachments, IDictionary metadata, Assistants.MessageRole role, IList content, IDictionary additionalBinaryDataProperties) { - Role = role; - Content = content; Attachments = attachments; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + Role = role; + Content = content; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public IList Attachments { get; set; } + public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/MessageDeletionResult.Serialization.cs b/src/Generated/Models/MessageDeletionResult.Serialization.cs index 0025d8dcf..89878ba0a 100644 --- a/src/Generated/Models/MessageDeletionResult.Serialization.cs +++ b/src/Generated/Models/MessageDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class MessageDeletionResult : IJsonModel { + internal MessageDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(MessageDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(MessageId); - } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Deleted); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(MessageId); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - MessageDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(MessageDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeMessageDeletionResult(document.RootElement, options); } - internal static MessageDeletionResult DeserializeMessageDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageDeletionResult DeserializeMessageDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; bool deleted = default; + string messageId = default; InternalDeleteMessageResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("id"u8)) { - deleted = property.Value.GetBoolean(); + messageId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteMessageResponseObject(property.Value.GetString()); + @object = new InternalDeleteMessageResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new MessageDeletionResult(id, deleted, @object, serializedAdditionalRawData); + return new MessageDeletionResult(deleted, messageId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - MessageDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeMessageDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ MessageDeletionResult IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageDeletionResult messageDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageDeletionResult(document.RootElement); + if (messageDeletionResult == null) + { + return null; + } + return BinaryContent.Create(messageDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageDeletionResult.cs b/src/Generated/Models/MessageDeletionResult.cs index c99f9922a..e2cf6d328 100644 --- a/src/Generated/Models/MessageDeletionResult.cs +++ b/src/Generated/Models/MessageDeletionResult.cs @@ -9,26 +9,28 @@ namespace OpenAI.Assistants { public partial class MessageDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal MessageDeletionResult(string messageId, bool deleted) - { - Argument.AssertNotNull(messageId, nameof(messageId)); + private protected IDictionary _additionalBinaryDataProperties; - MessageId = messageId; + internal MessageDeletionResult(bool deleted, string messageId) + { Deleted = deleted; + MessageId = messageId; } - internal MessageDeletionResult(string messageId, bool deleted, InternalDeleteMessageResponseObject @object, IDictionary serializedAdditionalRawData) + internal MessageDeletionResult(bool deleted, string messageId, InternalDeleteMessageResponseObject @object, IDictionary additionalBinaryDataProperties) { - MessageId = messageId; Deleted = deleted; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + MessageId = messageId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal MessageDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public bool Deleted { get; } } } diff --git a/src/Generated/Models/MessageFailureDetails.Serialization.cs b/src/Generated/Models/MessageFailureDetails.Serialization.cs index 50740a3cd..c76295571 100644 --- a/src/Generated/Models/MessageFailureDetails.Serialization.cs +++ b/src/Generated/Models/MessageFailureDetails.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class MessageFailureDetails : IJsonModel { + internal MessageFailureDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(MessageFailureDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("reason") != true) + if (_additionalBinaryDataProperties?.ContainsKey("reason") != true) { writer.WritePropertyName("reason"u8); writer.WriteStringValue(Reason.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - MessageFailureDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageFailureDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageFailureDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(MessageFailureDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeMessageFailureDetails(document.RootElement, options); } - internal static MessageFailureDetails DeserializeMessageFailureDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageFailureDetails DeserializeMessageFailureDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } MessageFailureReason reason = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("reason"u8)) + if (prop.NameEquals("reason"u8)) { - reason = new MessageFailureReason(property.Value.GetString()); + reason = new MessageFailureReason(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new MessageFailureDetails(reason, serializedAdditionalRawData); + return new MessageFailureDetails(reason, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - MessageFailureDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageFailureDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageFailureDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeMessageFailureDetails(document.RootElement, options); } default: @@ -119,15 +126,20 @@ MessageFailureDetails IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageFailureDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageFailureDetails messageFailureDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageFailureDetails(document.RootElement); + if (messageFailureDetails == null) + { + return null; + } + return BinaryContent.Create(messageFailureDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageFailureDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeMessageFailureDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageFailureDetails.cs b/src/Generated/Models/MessageFailureDetails.cs index 9c6b6e8e6..97711d979 100644 --- a/src/Generated/Models/MessageFailureDetails.cs +++ b/src/Generated/Models/MessageFailureDetails.cs @@ -9,22 +9,25 @@ namespace OpenAI.Assistants { public partial class MessageFailureDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal MessageFailureDetails(MessageFailureReason reason) { Reason = reason; } - internal MessageFailureDetails(MessageFailureReason reason, IDictionary serializedAdditionalRawData) + internal MessageFailureDetails(MessageFailureReason reason, IDictionary additionalBinaryDataProperties) { Reason = reason; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal MessageFailureDetails() + public MessageFailureReason Reason { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public MessageFailureReason Reason { get; } } } diff --git a/src/Generated/Models/MessageFailureReason.cs b/src/Generated/Models/MessageFailureReason.cs index ac0b0a02f..887e1efd7 100644 --- a/src/Generated/Models/MessageFailureReason.cs +++ b/src/Generated/Models/MessageFailureReason.cs @@ -4,39 +4,50 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct MessageFailureReason : IEquatable { private readonly string _value; - - public MessageFailureReason(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string ContentFilterValue = "content_filter"; private const string MaxTokensValue = "max_tokens"; private const string RunCancelledValue = "run_cancelled"; private const string RunExpiredValue = "run_expired"; private const string RunFailedValue = "run_failed"; + public MessageFailureReason(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static MessageFailureReason ContentFilter { get; } = new MessageFailureReason(ContentFilterValue); + public static MessageFailureReason MaxTokens { get; } = new MessageFailureReason(MaxTokensValue); + public static MessageFailureReason RunCancelled { get; } = new MessageFailureReason(RunCancelledValue); + public static MessageFailureReason RunExpired { get; } = new MessageFailureReason(RunExpiredValue); + public static MessageFailureReason RunFailed { get; } = new MessageFailureReason(RunFailedValue); + public static bool operator ==(MessageFailureReason left, MessageFailureReason right) => left.Equals(right); + public static bool operator !=(MessageFailureReason left, MessageFailureReason right) => !left.Equals(right); + public static implicit operator MessageFailureReason(string value) => new MessageFailureReason(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is MessageFailureReason other && Equals(other); + public bool Equals(MessageFailureReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/MessageModificationOptions.Serialization.cs b/src/Generated/Models/MessageModificationOptions.Serialization.cs index f5b28713b..a80017c74 100644 --- a/src/Generated/Models/MessageModificationOptions.Serialization.cs +++ b/src/Generated/Models/MessageModificationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,14 +15,19 @@ public partial class MessageModificationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(MessageModificationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -30,18 +36,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -49,7 +60,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -58,62 +69,65 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - MessageModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual MessageModificationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(MessageModificationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeMessageModificationOptions(document.RootElement, options); } - internal static MessageModificationOptions DeserializeMessageModificationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageModificationOptions DeserializeMessageModificationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new MessageModificationOptions(metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new MessageModificationOptions(metadata ?? new ChangeTrackingDictionary(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +137,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - MessageModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + MessageModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual MessageModificationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeMessageModificationOptions(document.RootElement, options); } default: @@ -141,15 +156,20 @@ MessageModificationOptions IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static MessageModificationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(MessageModificationOptions messageModificationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageModificationOptions(document.RootElement); + if (messageModificationOptions == null) + { + return null; + } + return BinaryContent.Create(messageModificationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator MessageModificationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeMessageModificationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/MessageModificationOptions.cs b/src/Generated/Models/MessageModificationOptions.cs index 5c53d2234..3818571f7 100644 --- a/src/Generated/Models/MessageModificationOptions.cs +++ b/src/Generated/Models/MessageModificationOptions.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class MessageModificationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public MessageModificationOptions() { Metadata = new ChangeTrackingDictionary(); } - internal MessageModificationOptions(IDictionary metadata, IDictionary serializedAdditionalRawData) + internal MessageModificationOptions(IDictionary metadata, IDictionary additionalBinaryDataProperties) { Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/MessageRole.Serialization.cs b/src/Generated/Models/MessageRole.Serialization.cs index 6d77ee639..33366fef5 100644 --- a/src/Generated/Models/MessageRole.Serialization.cs +++ b/src/Generated/Models/MessageRole.Serialization.cs @@ -8,17 +8,23 @@ namespace OpenAI.Assistants { internal static partial class MessageRoleExtensions { - public static string ToSerialString(this MessageRole value) => value switch + public static string ToSerialString(this Assistants.MessageRole value) => value switch { - MessageRole.User => "user", - MessageRole.Assistant => "assistant", + Assistants.MessageRole.User => "user", + Assistants.MessageRole.Assistant => "assistant", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown MessageRole value.") }; - public static MessageRole ToMessageRole(this string value) + public static Assistants.MessageRole ToMessageRole(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "user")) return MessageRole.User; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistant")) return MessageRole.Assistant; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "user")) + { + return Assistants.MessageRole.User; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "assistant")) + { + return Assistants.MessageRole.Assistant; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown MessageRole value."); } } diff --git a/src/Generated/Models/MessageStatus.cs b/src/Generated/Models/MessageStatus.cs index 86f1d414c..350d35e2e 100644 --- a/src/Generated/Models/MessageStatus.cs +++ b/src/Generated/Models/MessageStatus.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct MessageStatus : IEquatable { private readonly string _value; + private const string InProgressValue = "in_progress"; + private const string IncompleteValue = "incomplete"; + private const string CompletedValue = "completed"; public MessageStatus(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string InProgressValue = "in_progress"; - private const string IncompleteValue = "incomplete"; - private const string CompletedValue = "completed"; + _value = value; + } public static MessageStatus InProgress { get; } = new MessageStatus(InProgressValue); + public static MessageStatus Incomplete { get; } = new MessageStatus(IncompleteValue); + public static MessageStatus Completed { get; } = new MessageStatus(CompletedValue); + public static bool operator ==(MessageStatus left, MessageStatus right) => left.Equals(right); + public static bool operator !=(MessageStatus left, MessageStatus right) => !left.Equals(right); + public static implicit operator MessageStatus(string value) => new MessageStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is MessageStatus other && Equals(other); + public bool Equals(MessageStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/ModelDeletionResult.Serialization.cs b/src/Generated/Models/ModelDeletionResult.Serialization.cs index 0339219c0..71fe7aeca 100644 --- a/src/Generated/Models/ModelDeletionResult.Serialization.cs +++ b/src/Generated/Models/ModelDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Models { public partial class ModelDeletionResult : IJsonModel { + internal ModelDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ModelDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(ModelId); - } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Deleted); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(ModelId); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri #endif } } - writer.WriteEndObject(); } - ModelDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ModelDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ModelDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ModelDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeModelDeletionResult(document.RootElement, options); } - internal static ModelDeletionResult DeserializeModelDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ModelDeletionResult DeserializeModelDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; bool deleted = default; + string modelId = default; InternalDeleteModelResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("id"u8)) { - deleted = property.Value.GetBoolean(); + modelId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteModelResponseObject(property.Value.GetString()); + @object = new InternalDeleteModelResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ModelDeletionResult(id, deleted, @object, serializedAdditionalRawData); + return new ModelDeletionResult(deleted, modelId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ModelDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ModelDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ModelDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeModelDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ ModelDeletionResult IPersistableModel.Create(BinaryData dat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModelDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ModelDeletionResult modelDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeModelDeletionResult(document.RootElement); + if (modelDeletionResult == null) + { + return null; + } + return BinaryContent.Create(modelDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ModelDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeModelDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ModelDeletionResult.cs b/src/Generated/Models/ModelDeletionResult.cs index d70e155fe..4949c007d 100644 --- a/src/Generated/Models/ModelDeletionResult.cs +++ b/src/Generated/Models/ModelDeletionResult.cs @@ -9,26 +9,28 @@ namespace OpenAI.Models { public partial class ModelDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ModelDeletionResult(string modelId, bool deleted) - { - Argument.AssertNotNull(modelId, nameof(modelId)); + private protected IDictionary _additionalBinaryDataProperties; - ModelId = modelId; + internal ModelDeletionResult(bool deleted, string modelId) + { Deleted = deleted; + ModelId = modelId; } - internal ModelDeletionResult(string modelId, bool deleted, InternalDeleteModelResponseObject @object, IDictionary serializedAdditionalRawData) + internal ModelDeletionResult(bool deleted, string modelId, InternalDeleteModelResponseObject @object, IDictionary additionalBinaryDataProperties) { - ModelId = modelId; Deleted = deleted; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + ModelId = modelId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ModelDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public bool Deleted { get; } } } diff --git a/src/Generated/Models/ModerationApplicableInputKinds.Serialization.cs b/src/Generated/Models/ModerationApplicableInputKinds.Serialization.cs index a098947a7..7c0c4efc2 100644 --- a/src/Generated/Models/ModerationApplicableInputKinds.Serialization.cs +++ b/src/Generated/Models/ModerationApplicableInputKinds.Serialization.cs @@ -2,8 +2,6 @@ #nullable disable -using System; - namespace OpenAI.Moderations { internal static partial class ModerationApplicableInputKindsExtensions diff --git a/src/Generated/Models/ModerationOptions.Serialization.cs b/src/Generated/Models/ModerationOptions.Serialization.cs index 591577235..5c837bec3 100644 --- a/src/Generated/Models/ModerationOptions.Serialization.cs +++ b/src/Generated/Models/ModerationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { @@ -14,18 +15,23 @@ internal partial class ModerationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ModerationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("input") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input") != true) { writer.WritePropertyName("input"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(Input); + writer.WriteRawValue(Input); #else using (JsonDocument document = JsonDocument.Parse(Input)) { @@ -33,14 +39,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } #endif } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(Model)) + if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.Value.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -48,7 +54,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -57,63 +63,59 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite #endif } } - writer.WriteEndObject(); } - ModerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ModerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ModerationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ModerationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeModerationOptions(document.RootElement, options); } - internal static ModerationOptions DeserializeModerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ModerationOptions DeserializeModerationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } BinaryData input = default; InternalCreateModerationRequestModel? model = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("input"u8)) + if (prop.NameEquals("input"u8)) { - input = BinaryData.FromString(property.Value.GetRawText()); + input = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - model = new InternalCreateModerationRequestModel(property.Value.GetString()); + model = new InternalCreateModerationRequestModel(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ModerationOptions(input, model, serializedAdditionalRawData); + return new ModerationOptions(input, model, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +125,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions o } } - ModerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ModerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ModerationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeModerationOptions(document.RootElement, options); } default: @@ -141,15 +144,20 @@ ModerationOptions IPersistableModel.Create(BinaryData data, M string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ModerationOptions moderationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationOptions(document.RootElement); + if (moderationOptions == null) + { + return null; + } + return BinaryContent.Create(moderationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ModerationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeModerationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ModerationOptions.cs b/src/Generated/Models/ModerationOptions.cs index e21defe31..9aeee81f9 100644 --- a/src/Generated/Models/ModerationOptions.cs +++ b/src/Generated/Models/ModerationOptions.cs @@ -9,13 +9,19 @@ namespace OpenAI.Moderations { internal partial class ModerationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ModerationOptions(BinaryData input, InternalCreateModerationRequestModel? model, IDictionary serializedAdditionalRawData) + internal ModerationOptions(BinaryData input, InternalCreateModerationRequestModel? model, IDictionary additionalBinaryDataProperties) { Input = input; Model = model; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ModerationResult.Serialization.cs b/src/Generated/Models/ModerationResult.Serialization.cs index f419fc8e6..f889b6dd1 100644 --- a/src/Generated/Models/ModerationResult.Serialization.cs +++ b/src/Generated/Models/ModerationResult.Serialization.cs @@ -6,27 +6,63 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { public partial class ModerationResult : IJsonModel { - ModerationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ModerationResult)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("flagged") != true) + { + writer.WritePropertyName("flagged"u8); + writer.WriteBooleanValue(Flagged); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ModerationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual ModerationResult 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(ModerationResult)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeModerationResult(document.RootElement, options); + return ModerationResult.DeserializeModerationResult(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +72,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ModerationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ModerationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ModerationResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeModerationResult(document.RootElement, options); + return ModerationResult.DeserializeModerationResult(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ModerationResult)} does not support reading '{options.Format}' format."); @@ -54,15 +91,20 @@ ModerationResult IPersistableModel.Create(BinaryData data, Mod string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ModerationResult moderationResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationResult(document.RootElement); + if (moderationResult == null) + { + return null; + } + return BinaryContent.Create(moderationResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ModerationResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ModerationResult.DeserializeModerationResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ModerationResult.cs b/src/Generated/Models/ModerationResult.cs index 292988ade..090d8a0b9 100644 --- a/src/Generated/Models/ModerationResult.cs +++ b/src/Generated/Models/ModerationResult.cs @@ -9,6 +9,25 @@ namespace OpenAI.Moderations { public partial class ModerationResult { + private protected IDictionary _additionalBinaryDataProperties; + + internal ModerationResult(bool flagged) + { + Flagged = flagged; + } + + internal ModerationResult(bool flagged, IDictionary additionalBinaryDataProperties) + { + Flagged = flagged; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + public bool Flagged { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ModerationResultCollection.Serialization.cs b/src/Generated/Models/ModerationResultCollection.Serialization.cs index c0697ccd4..979673c2b 100644 --- a/src/Generated/Models/ModerationResultCollection.Serialization.cs +++ b/src/Generated/Models/ModerationResultCollection.Serialization.cs @@ -6,27 +6,68 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Moderations { public partial class ModerationResultCollection : IJsonModel { - ModerationResultCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationResultCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ModerationResultCollection)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + ModerationResultCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ModerationResultCollection 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(ModerationResultCollection)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeModerationResultCollection(document.RootElement, options); + return ModerationResultCollection.DeserializeModerationResultCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +77,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - ModerationResultCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ModerationResultCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ModerationResultCollection 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeModerationResultCollection(document.RootElement, options); + return ModerationResultCollection.DeserializeModerationResultCollection(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ModerationResultCollection)} does not support reading '{options.Format}' format."); @@ -54,15 +96,20 @@ ModerationResultCollection IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationResultCollection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ModerationResultCollection moderationResultCollection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationResultCollection(document.RootElement); + if (moderationResultCollection == null) + { + return null; + } + return BinaryContent.Create(moderationResultCollection, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ModerationResultCollection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ModerationResultCollection.DeserializeModerationResultCollection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ModerationResultCollection.cs b/src/Generated/Models/ModerationResultCollection.cs index dd88f801f..db1da9699 100644 --- a/src/Generated/Models/ModerationResultCollection.cs +++ b/src/Generated/Models/ModerationResultCollection.cs @@ -2,15 +2,23 @@ #nullable disable +using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; namespace OpenAI.Moderations { - public partial class ModerationResultCollection : ReadOnlyCollection + public partial class ModerationResultCollection { + private protected IDictionary _additionalBinaryDataProperties; + public string Id { get; } + public string Model { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIEmbedding.Serialization.cs b/src/Generated/Models/OpenAIEmbedding.Serialization.cs index 090448d73..a826e0c51 100644 --- a/src/Generated/Models/OpenAIEmbedding.Serialization.cs +++ b/src/Generated/Models/OpenAIEmbedding.Serialization.cs @@ -7,30 +7,40 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Embeddings { public partial class OpenAIEmbedding : IJsonModel { + internal OpenAIEmbedding() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(OpenAIEmbedding)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("embedding") != true) + if (_additionalBinaryDataProperties?.ContainsKey("embedding") != true) { writer.WritePropertyName("embedding"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(EmbeddingProperty); + writer.WriteRawValue(EmbeddingProperty); #else using (JsonDocument document = JsonDocument.Parse(EmbeddingProperty)) { @@ -38,14 +48,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO } #endif } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -53,7 +63,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -62,65 +72,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO #endif } } - writer.WriteEndObject(); } - OpenAIEmbedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIEmbedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual OpenAIEmbedding JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(OpenAIEmbedding)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeOpenAIEmbedding(document.RootElement, options); } - internal static OpenAIEmbedding DeserializeOpenAIEmbedding(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIEmbedding DeserializeOpenAIEmbedding(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } int index = default; - BinaryData embedding = default; + BinaryData embeddingProperty = default; InternalEmbeddingObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("embedding"u8)) + if (prop.NameEquals("embedding"u8)) { - embedding = BinaryData.FromString(property.Value.GetRawText()); + embeddingProperty = BinaryData.FromString(prop.Value.GetRawText()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalEmbeddingObject(property.Value.GetString()); + @object = new InternalEmbeddingObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new OpenAIEmbedding(index, embedding, @object, serializedAdditionalRawData); + return new OpenAIEmbedding(index, embeddingProperty, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -130,15 +136,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - OpenAIEmbedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIEmbedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIEmbedding 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeOpenAIEmbedding(document.RootElement, options); } default: @@ -148,15 +155,20 @@ OpenAIEmbedding IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIEmbedding FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIEmbedding openAIEmbedding) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIEmbedding(document.RootElement); + if (openAIEmbedding == null) + { + return null; + } + return BinaryContent.Create(openAIEmbedding, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIEmbedding(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIEmbedding(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIEmbedding.cs b/src/Generated/Models/OpenAIEmbedding.cs index a3b0b1aad..415eae6a6 100644 --- a/src/Generated/Models/OpenAIEmbedding.cs +++ b/src/Generated/Models/OpenAIEmbedding.cs @@ -9,12 +9,14 @@ namespace OpenAI.Embeddings { public partial class OpenAIEmbedding { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal OpenAIEmbedding() + public int Index { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public int Index { get; } } } diff --git a/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs b/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs index f025c25a0..990343e1b 100644 --- a/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs +++ b/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs @@ -6,27 +6,73 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Embeddings { public partial class OpenAIEmbeddingCollection : IJsonModel { - OpenAIEmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (_additionalBinaryDataProperties?.ContainsKey("usage") != true) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } } + } + + OpenAIEmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual OpenAIEmbeddingCollection 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(OpenAIEmbeddingCollection)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIEmbeddingCollection(document.RootElement, options); + return OpenAIEmbeddingCollection.DeserializeOpenAIEmbeddingCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +82,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - OpenAIEmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIEmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIEmbeddingCollection 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIEmbeddingCollection(document.RootElement, options); + return OpenAIEmbeddingCollection.DeserializeOpenAIEmbeddingCollection(document.RootElement, options); } default: throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support reading '{options.Format}' format."); @@ -54,15 +101,20 @@ OpenAIEmbeddingCollection IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIEmbeddingCollection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIEmbeddingCollection openAIEmbeddingCollection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIEmbeddingCollection(document.RootElement); + if (openAIEmbeddingCollection == null) + { + return null; + } + return BinaryContent.Create(openAIEmbeddingCollection, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIEmbeddingCollection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return OpenAIEmbeddingCollection.DeserializeOpenAIEmbeddingCollection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIEmbeddingCollection.cs b/src/Generated/Models/OpenAIEmbeddingCollection.cs index 50b716a99..d0e49a974 100644 --- a/src/Generated/Models/OpenAIEmbeddingCollection.cs +++ b/src/Generated/Models/OpenAIEmbeddingCollection.cs @@ -2,16 +2,23 @@ #nullable disable +using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; namespace OpenAI.Embeddings { - public partial class OpenAIEmbeddingCollection : ReadOnlyCollection + public partial class OpenAIEmbeddingCollection { + private protected IDictionary _additionalBinaryDataProperties; + public string Model { get; } public EmbeddingTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIError.Serialization.cs b/src/Generated/Models/OpenAIError.Serialization.cs index 6bc1f6fc5..5cafbaa12 100644 --- a/src/Generated/Models/OpenAIError.Serialization.cs +++ b/src/Generated/Models/OpenAIError.Serialization.cs @@ -7,21 +7,31 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { internal partial class OpenAIError : IJsonModel { + internal OpenAIError() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(OpenAIError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) + if (_additionalBinaryDataProperties?.ContainsKey("code") != true) { if (Code != null) { @@ -30,15 +40,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } else { - writer.WriteNull("code"); + writer.WriteNull("code"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData?.ContainsKey("param") != true) + if (_additionalBinaryDataProperties?.ContainsKey("param") != true) { if (Param != null) { @@ -47,17 +57,17 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } else { - writer.WriteNull("param"); + writer.WriteNull("param"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -65,7 +75,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -74,81 +84,77 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio #endif } } - writer.WriteEndObject(); } - OpenAIError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual OpenAIError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(OpenAIError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeOpenAIError(document.RootElement, options); } - internal static OpenAIError DeserializeOpenAIError(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIError DeserializeOpenAIError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string code = default; string message = default; - string param = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @param = default; + string @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { code = null; continue; } - code = property.Value.GetString(); + code = prop.Value.GetString(); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } - if (property.NameEquals("param"u8)) + if (prop.NameEquals("param"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - param = null; + @param = null; continue; } - param = property.Value.GetString(); + @param = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new OpenAIError(code, message, param, type, serializedAdditionalRawData); + return new OpenAIError(code, message, @param, @type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -158,15 +164,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options } } - OpenAIError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeOpenAIError(document.RootElement, options); } default: @@ -176,15 +183,20 @@ OpenAIError IPersistableModel.Create(BinaryData data, ModelReaderWr string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIError openAIError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIError(document.RootElement); + if (openAIError == null) + { + return null; + } + return BinaryContent.Create(openAIError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIError.cs b/src/Generated/Models/OpenAIError.cs index 7b94f06f3..ac7c03ed9 100644 --- a/src/Generated/Models/OpenAIError.cs +++ b/src/Generated/Models/OpenAIError.cs @@ -9,34 +9,37 @@ namespace OpenAI.Internal { internal partial class OpenAIError { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal OpenAIError(string code, string message, string param, string type) - { - Argument.AssertNotNull(message, nameof(message)); - Argument.AssertNotNull(type, nameof(type)); + private protected IDictionary _additionalBinaryDataProperties; + internal OpenAIError(string code, string message, string @param, string @type) + { Code = code; Message = message; - Param = param; - Type = type; + Param = @param; + Type = @type; } - internal OpenAIError(string code, string message, string param, string type, IDictionary serializedAdditionalRawData) + internal OpenAIError(string code, string message, string @param, string @type, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - Param = param; - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal OpenAIError() - { + Param = @param; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Code { get; } + public string Message { get; } + public string Param { get; } + public string Type { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIErrorResponse.Serialization.cs b/src/Generated/Models/OpenAIErrorResponse.Serialization.cs index e78630aea..a433d4027 100644 --- a/src/Generated/Models/OpenAIErrorResponse.Serialization.cs +++ b/src/Generated/Models/OpenAIErrorResponse.Serialization.cs @@ -7,28 +7,38 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Internal { internal partial class OpenAIErrorResponse : IJsonModel { + internal OpenAIErrorResponse() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(OpenAIErrorResponse)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("error") != true) { writer.WritePropertyName("error"u8); writer.WriteObjectValue(Error, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,53 +55,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri #endif } } - writer.WriteEndObject(); } - OpenAIErrorResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIErrorResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual OpenAIErrorResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(OpenAIErrorResponse)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeOpenAIErrorResponse(document.RootElement, options); } - internal static OpenAIErrorResponse DeserializeOpenAIErrorResponse(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIErrorResponse DeserializeOpenAIErrorResponse(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } OpenAIError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("error"u8)) + if (prop.NameEquals("error"u8)) { - error = OpenAIError.DeserializeOpenAIError(property.Value, options); + error = OpenAIError.DeserializeOpenAIError(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new OpenAIErrorResponse(error, serializedAdditionalRawData); + return new OpenAIErrorResponse(error, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - OpenAIErrorResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIErrorResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIErrorResponse 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeOpenAIErrorResponse(document.RootElement, options); } default: @@ -119,15 +126,20 @@ OpenAIErrorResponse IPersistableModel.Create(BinaryData dat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIErrorResponse FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIErrorResponse openAIErrorResponse) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIErrorResponse(document.RootElement); + if (openAIErrorResponse == null) + { + return null; + } + return BinaryContent.Create(openAIErrorResponse, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIErrorResponse(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIErrorResponse(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIErrorResponse.cs b/src/Generated/Models/OpenAIErrorResponse.cs index 764dd3854..46308908b 100644 --- a/src/Generated/Models/OpenAIErrorResponse.cs +++ b/src/Generated/Models/OpenAIErrorResponse.cs @@ -9,24 +9,25 @@ namespace OpenAI.Internal { internal partial class OpenAIErrorResponse { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal OpenAIErrorResponse(OpenAIError error) { - Argument.AssertNotNull(error, nameof(error)); - Error = error; } - internal OpenAIErrorResponse(OpenAIError error, IDictionary serializedAdditionalRawData) + internal OpenAIErrorResponse(OpenAIError error, IDictionary additionalBinaryDataProperties) { Error = error; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal OpenAIErrorResponse() + public OpenAIError Error { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public OpenAIError Error { get; } } } diff --git a/src/Generated/Models/OpenAIFile.Serialization.cs b/src/Generated/Models/OpenAIFile.Serialization.cs index 0e3815cd6..38a759cfb 100644 --- a/src/Generated/Models/OpenAIFile.Serialization.cs +++ b/src/Generated/Models/OpenAIFile.Serialization.cs @@ -7,70 +7,80 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { public partial class OpenAIFile : IJsonModel { + internal OpenAIFile() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(OpenAIFile)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("bytes") != true) - { - if (SizeInBytes != null) - { - writer.WritePropertyName("bytes"u8); - writer.WriteNumberValue(SizeInBytes.Value); - } - else - { - writer.WriteNull("bytes"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("filename") != true) + if (_additionalBinaryDataProperties?.ContainsKey("filename") != true) { writer.WritePropertyName("filename"u8); writer.WriteStringValue(Filename); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("purpose") != true) + { + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToSerialString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("purpose") != true) + if (_additionalBinaryDataProperties?.ContainsKey("bytes") != true) { - writer.WritePropertyName("purpose"u8); - writer.WriteStringValue(Purpose.ToSerialString()); + if (SizeInBytes != null) + { + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(SizeInBytes.Value); + } + else + { + writer.WriteNull("bytes"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("status_details") != true && Optional.IsDefined(StatusDetails)) + if (Optional.IsDefined(StatusDetails) && _additionalBinaryDataProperties?.ContainsKey("status_details") != true) { writer.WritePropertyName("status_details"u8); writer.WriteStringValue(StatusDetails); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -78,7 +88,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOption } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -87,109 +97,105 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOption #endif } } - writer.WriteEndObject(); } - OpenAIFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual OpenAIFile JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeOpenAIFile(document.RootElement, options); } - internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - int? bytes = default; DateTimeOffset createdAt = default; string filename = default; + Files.FilePurpose purpose = default; InternalOpenAIFileObject @object = default; - FilePurpose purpose = default; - FileStatus status = default; + int? sizeInBytes = default; + Files.FileStatus status = default; string statusDetails = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("bytes"u8)) + if (prop.NameEquals("created_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - bytes = null; - continue; - } - bytes = property.Value.GetInt32(); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("filename"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + filename = prop.Value.GetString(); continue; } - if (property.NameEquals("filename"u8)) + if (prop.NameEquals("purpose"u8)) { - filename = property.Value.GetString(); + purpose = prop.Value.GetString().ToFilePurpose(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalOpenAIFileObject(property.Value.GetString()); + @object = new InternalOpenAIFileObject(prop.Value.GetString()); continue; } - if (property.NameEquals("purpose"u8)) + if (prop.NameEquals("bytes"u8)) { - purpose = property.Value.GetString().ToFilePurpose(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + sizeInBytes = null; + continue; + } + sizeInBytes = prop.Value.GetInt32(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = property.Value.GetString().ToFileStatus(); + status = prop.Value.GetString().ToFileStatus(); continue; } - if (property.NameEquals("status_details"u8)) + if (prop.NameEquals("status_details"u8)) { - statusDetails = property.Value.GetString(); + statusDetails = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new OpenAIFile( id, - bytes, createdAt, filename, - @object, purpose, + @object, + sizeInBytes, status, statusDetails, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -199,15 +205,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIFile 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeOpenAIFile(document.RootElement, options); } default: @@ -217,15 +224,20 @@ OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWrit string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIFile FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIFile openAIFile) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIFile(document.RootElement); + if (openAIFile == null) + { + return null; + } + return BinaryContent.Create(openAIFile, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIFile(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIFile(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIFile.cs b/src/Generated/Models/OpenAIFile.cs index 23577b777..aad4ac9f8 100644 --- a/src/Generated/Models/OpenAIFile.cs +++ b/src/Generated/Models/OpenAIFile.cs @@ -9,41 +9,43 @@ namespace OpenAI.Files { public partial class OpenAIFile { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal OpenAIFile(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, FilePurpose purpose, FileStatus status) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(filename, nameof(filename)); + private protected IDictionary _additionalBinaryDataProperties; + internal OpenAIFile(string id, DateTimeOffset createdAt, string filename, Files.FilePurpose purpose, int? sizeInBytes, Files.FileStatus status) + { Id = id; - SizeInBytes = sizeInBytes; CreatedAt = createdAt; Filename = filename; Purpose = purpose; + SizeInBytes = sizeInBytes; Status = status; } - internal OpenAIFile(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, InternalOpenAIFileObject @object, FilePurpose purpose, FileStatus status, string statusDetails, IDictionary serializedAdditionalRawData) + internal OpenAIFile(string id, DateTimeOffset createdAt, string filename, Files.FilePurpose purpose, InternalOpenAIFileObject @object, int? sizeInBytes, Files.FileStatus status, string statusDetails, IDictionary additionalBinaryDataProperties) { Id = id; - SizeInBytes = sizeInBytes; CreatedAt = createdAt; Filename = filename; - Object = @object; Purpose = purpose; + this.Object = @object; + SizeInBytes = sizeInBytes; Status = status; StatusDetails = statusDetails; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal OpenAIFile() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } + public DateTimeOffset CreatedAt { get; } + public string Filename { get; } - public FilePurpose Purpose { get; } + public Files.FilePurpose Purpose { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIFileCollection.Serialization.cs b/src/Generated/Models/OpenAIFileCollection.Serialization.cs index 5ed78de47..4c04572bb 100644 --- a/src/Generated/Models/OpenAIFileCollection.Serialization.cs +++ b/src/Generated/Models/OpenAIFileCollection.Serialization.cs @@ -6,27 +6,63 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Files { public partial class OpenAIFileCollection : IJsonModel { - OpenAIFileCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAIFileCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual OpenAIFileCollection 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(OpenAIFileCollection)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIFileCollection(document.RootElement, options); + return OpenAIFileCollection.DeserializeOpenAIFileCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +72,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - OpenAIFileCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIFileCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIFileCollection 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIFileCollection(document.RootElement, options); + return OpenAIFileCollection.DeserializeOpenAIFileCollection(document.RootElement, options); } default: throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support reading '{options.Format}' format."); @@ -54,15 +91,20 @@ OpenAIFileCollection IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIFileCollection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIFileCollection openAIFileCollection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIFileCollection(document.RootElement); + if (openAIFileCollection == null) + { + return null; + } + return BinaryContent.Create(openAIFileCollection, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIFileCollection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return OpenAIFileCollection.DeserializeOpenAIFileCollection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIFileCollection.cs b/src/Generated/Models/OpenAIFileCollection.cs index b868860e4..7ba8ee002 100644 --- a/src/Generated/Models/OpenAIFileCollection.cs +++ b/src/Generated/Models/OpenAIFileCollection.cs @@ -2,13 +2,19 @@ #nullable disable +using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; namespace OpenAI.Files { - public partial class OpenAIFileCollection : ReadOnlyCollection + public partial class OpenAIFileCollection { + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIModel.Serialization.cs b/src/Generated/Models/OpenAIModel.Serialization.cs index 4d230a105..01de3b396 100644 --- a/src/Generated/Models/OpenAIModel.Serialization.cs +++ b/src/Generated/Models/OpenAIModel.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Models { public partial class OpenAIModel : IJsonModel { + internal OpenAIModel() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(OpenAIModel)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("created") != true) + if (_additionalBinaryDataProperties?.ContainsKey("owned_by") != true) { - writer.WritePropertyName("created"u8); - writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("owned_by"u8); + writer.WriteStringValue(OwnedBy); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("owned_by") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) { - writer.WritePropertyName("owned_by"u8); - writer.WriteStringValue(OwnedBy); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,71 +70,67 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio #endif } } - writer.WriteEndObject(); } - OpenAIModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual OpenAIModel JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(OpenAIModel)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeOpenAIModel(document.RootElement, options); } - internal static OpenAIModel DeserializeOpenAIModel(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIModel DeserializeOpenAIModel(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - DateTimeOffset created = default; - InternalModelObject @object = default; string ownedBy = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalModelObject @object = default; + DateTimeOffset createdAt = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created"u8)) + if (prop.NameEquals("owned_by"u8)) { - created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + ownedBy = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalModelObject(property.Value.GetString()); + @object = new InternalModelObject(prop.Value.GetString()); continue; } - if (property.NameEquals("owned_by"u8)) + if (prop.NameEquals("created"u8)) { - ownedBy = property.Value.GetString(); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new OpenAIModel(id, created, @object, ownedBy, serializedAdditionalRawData); + return new OpenAIModel(id, ownedBy, @object, createdAt, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -134,15 +140,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options } } - OpenAIModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIModel 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeOpenAIModel(document.RootElement, options); } default: @@ -152,15 +159,20 @@ OpenAIModel IPersistableModel.Create(BinaryData data, ModelReaderWr string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIModel FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIModel openAIModel) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIModel(document.RootElement); + if (openAIModel == null) + { + return null; + } + return BinaryContent.Create(openAIModel, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIModel(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIModel(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIModel.cs b/src/Generated/Models/OpenAIModel.cs index 390f591ea..f531dd90f 100644 --- a/src/Generated/Models/OpenAIModel.cs +++ b/src/Generated/Models/OpenAIModel.cs @@ -9,32 +9,32 @@ namespace OpenAI.Models { public partial class OpenAIModel { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal OpenAIModel(string id, DateTimeOffset createdAt, string ownedBy) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(ownedBy, nameof(ownedBy)); + private protected IDictionary _additionalBinaryDataProperties; + internal OpenAIModel(string id, string ownedBy, DateTimeOffset createdAt) + { Id = id; - CreatedAt = createdAt; OwnedBy = ownedBy; + CreatedAt = createdAt; } - internal OpenAIModel(string id, DateTimeOffset createdAt, InternalModelObject @object, string ownedBy, IDictionary serializedAdditionalRawData) + internal OpenAIModel(string id, string ownedBy, InternalModelObject @object, DateTimeOffset createdAt, IDictionary additionalBinaryDataProperties) { Id = id; - CreatedAt = createdAt; - Object = @object; OwnedBy = ownedBy; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal OpenAIModel() - { + this.Object = @object; + CreatedAt = createdAt; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public string OwnedBy { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/OpenAIModelCollection.Serialization.cs b/src/Generated/Models/OpenAIModelCollection.Serialization.cs index 0d8747b09..d072b37c6 100644 --- a/src/Generated/Models/OpenAIModelCollection.Serialization.cs +++ b/src/Generated/Models/OpenAIModelCollection.Serialization.cs @@ -6,27 +6,63 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Models { public partial class OpenAIModelCollection : IJsonModel { - OpenAIModelCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIModelCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIModelCollection)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAIModelCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual OpenAIModelCollection 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(OpenAIModelCollection)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIModelCollection(document.RootElement, options); + return OpenAIModelCollection.DeserializeOpenAIModelCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -36,16 +72,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - OpenAIModelCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + OpenAIModelCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual OpenAIModelCollection 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIModelCollection(document.RootElement, options); + return OpenAIModelCollection.DeserializeOpenAIModelCollection(document.RootElement, options); } default: throw new FormatException($"The model {nameof(OpenAIModelCollection)} does not support reading '{options.Format}' format."); @@ -54,15 +91,20 @@ OpenAIModelCollection IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIModelCollection FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(OpenAIModelCollection openAIModelCollection) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIModelCollection(document.RootElement); + if (openAIModelCollection == null) + { + return null; + } + return BinaryContent.Create(openAIModelCollection, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator OpenAIModelCollection(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return OpenAIModelCollection.DeserializeOpenAIModelCollection(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/OpenAIModelCollection.cs b/src/Generated/Models/OpenAIModelCollection.cs index 08dc52d83..d655f1ee6 100644 --- a/src/Generated/Models/OpenAIModelCollection.cs +++ b/src/Generated/Models/OpenAIModelCollection.cs @@ -2,13 +2,19 @@ #nullable disable +using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; namespace OpenAI.Models { - public partial class OpenAIModelCollection : ReadOnlyCollection + public partial class OpenAIModelCollection { + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunCollectionOrder.cs b/src/Generated/Models/RunCollectionOrder.cs index ee88afced..d16dcacf3 100644 --- a/src/Generated/Models/RunCollectionOrder.cs +++ b/src/Generated/Models/RunCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public RunCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(RunCollectionOrder left, RunCollectionOrder right) => left.Equals(right); + public static bool operator !=(RunCollectionOrder left, RunCollectionOrder right) => !left.Equals(right); + public static implicit operator RunCollectionOrder(string value) => new RunCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunCollectionOrder other && Equals(other); + public bool Equals(RunCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunCreationOptions.Serialization.cs b/src/Generated/Models/RunCreationOptions.Serialization.cs index 2b255bd47..ee5dc6c45 100644 --- a/src/Generated/Models/RunCreationOptions.Serialization.cs +++ b/src/Generated/Models/RunCreationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,19 +15,48 @@ public partial class RunCreationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunCreationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("assistant_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true && Optional.IsDefined(ModelOverride)) + if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true) + { + if (Stream != null) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + else + { + writer.WriteNull("stream"u8); + } + } + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); + } + else + { + writer.WriteNull("responseFormat"u8); + } + } + if (Optional.IsDefined(ModelOverride) && _additionalBinaryDataProperties?.ContainsKey("model") != true) { if (ModelOverride != null) { @@ -35,10 +65,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("model"); + writer.WriteNull("model"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true && Optional.IsDefined(InstructionsOverride)) + if (Optional.IsDefined(InstructionsOverride) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true) { if (InstructionsOverride != null) { @@ -47,10 +77,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("instructions"); + writer.WriteNull("instructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("additional_instructions") != true && Optional.IsDefined(AdditionalInstructions)) + if (Optional.IsDefined(AdditionalInstructions) && _additionalBinaryDataProperties?.ContainsKey("additional_instructions") != true) { if (AdditionalInstructions != null) { @@ -59,44 +89,49 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("additional_instructions"); + writer.WriteNull("additionalInstructions"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("additional_messages") != true && Optional.IsCollectionDefined(InternalMessages)) + if (Optional.IsCollectionDefined(InternalMessages) && _additionalBinaryDataProperties?.ContainsKey("additional_messages") != true) { if (InternalMessages != null) { writer.WritePropertyName("additional_messages"u8); writer.WriteStartArray(); - foreach (var item in InternalMessages) + foreach (MessageCreationOptions item in InternalMessages) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } else { - writer.WriteNull("additional_messages"); + writer.WriteNull("additionalMessages"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true && Optional.IsCollectionDefined(ToolsOverride)) + if (Optional.IsDefined(AllowParallelToolCalls) && _additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); + } + if (Optional.IsCollectionDefined(ToolsOverride) && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { if (ToolsOverride != null) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in ToolsOverride) + foreach (ToolDefinition item in ToolsOverride) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } else { - writer.WriteNull("tools"); + writer.WriteNull("tools"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -105,16 +140,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -123,10 +163,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(NucleusSamplingFactor)) + if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { if (NucleusSamplingFactor != null) { @@ -135,22 +175,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("top_p"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("stream") != true && Optional.IsDefined(Stream)) - { - if (Stream != null) - { - writer.WritePropertyName("stream"u8); - writer.WriteBooleanValue(Stream.Value); - } - else - { - writer.WriteNull("stream"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_prompt_tokens") != true && Optional.IsDefined(MaxInputTokenCount)) + if (Optional.IsDefined(MaxInputTokenCount) && _additionalBinaryDataProperties?.ContainsKey("max_prompt_tokens") != true) { if (MaxInputTokenCount != null) { @@ -159,10 +187,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("max_prompt_tokens"); + writer.WriteNull("maxPromptTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_completion_tokens") != true && Optional.IsDefined(MaxOutputTokenCount)) + if (Optional.IsDefined(MaxOutputTokenCount) && _additionalBinaryDataProperties?.ContainsKey("max_completion_tokens") != true) { if (MaxOutputTokenCount != null) { @@ -171,10 +199,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("max_completion_tokens"); + writer.WriteNull("maxCompletionTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("truncation_strategy") != true && Optional.IsDefined(TruncationStrategy)) + if (Optional.IsDefined(TruncationStrategy) && _additionalBinaryDataProperties?.ContainsKey("truncation_strategy") != true) { if (TruncationStrategy != null) { @@ -183,41 +211,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } else { - writer.WriteNull("truncation_strategy"); + writer.WriteNull("truncationStrategy"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true && Optional.IsDefined(ToolConstraint)) + if (Optional.IsDefined(ToolConstraint) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { if (ToolConstraint != null) { writer.WritePropertyName("tool_choice"u8); - SerializeToolConstraint(writer, options); - } - else - { - writer.WriteNull("tool_choice"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(AllowParallelToolCalls)) - { - writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(AllowParallelToolCalls.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) - { - if (ResponseFormat != null) - { - writer.WritePropertyName("response_format"u8); - writer.WriteObjectValue(ResponseFormat, options); + this.SerializeToolConstraint(writer, options); } else { - writer.WriteNull("response_format"); + writer.WriteNull("toolChoice"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -225,7 +236,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -234,246 +245,249 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - RunCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunCreationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunCreationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunCreationOptions(document.RootElement, options); } - internal static RunCreationOptions DeserializeRunCreationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunCreationOptions DeserializeRunCreationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string assistantId = default; - string model = default; - string instructions = default; + bool? stream = default; + AssistantResponseFormat responseFormat = default; + string modelOverride = default; + string instructionsOverride = default; string additionalInstructions = default; - IList additionalMessages = default; - IList tools = default; + IList internalMessages = default; + bool? allowParallelToolCalls = default; + IList toolsOverride = default; IDictionary metadata = default; float? temperature = default; - float? topP = default; - bool? stream = default; - int? maxPromptTokens = default; - int? maxCompletionTokens = default; + float? nucleusSamplingFactor = default; + int? maxInputTokenCount = default; + int? maxOutputTokenCount = default; RunTruncationStrategy truncationStrategy = default; - ToolConstraint toolChoice = default; - bool? parallelToolCalls = default; - AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ToolConstraint toolConstraint = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("assistant_id"u8)) + if (prop.NameEquals("assistant_id"u8)) { - assistantId = property.Value.GetString(); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("stream"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - model = null; + stream = null; continue; } - model = property.Value.GetString(); + stream = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("response_format"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - instructions = null; + responseFormat = null; continue; } - instructions = property.Value.GetString(); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("additional_instructions"u8)) + if (prop.NameEquals("model"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - additionalInstructions = null; + modelOverride = null; continue; } - additionalInstructions = property.Value.GetString(); + modelOverride = prop.Value.GetString(); continue; } - if (property.NameEquals("additional_messages"u8)) + if (prop.NameEquals("instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + instructionsOverride = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(MessageCreationOptions.DeserializeMessageCreationOptions(item, options)); - } - additionalMessages = array; + instructionsOverride = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("additional_instructions"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + additionalInstructions = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); - } - tools = array; + additionalInstructions = prop.Value.GetString(); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("additional_messages"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + array.Add(MessageCreationOptions.DeserializeMessageCreationOptions(item, options)); } - metadata = dictionary; + internalMessages = array; continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("parallel_tool_calls"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - temperature = null; continue; } - temperature = property.Value.GetSingle(); + allowParallelToolCalls = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("tools"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; continue; } - topP = property.Value.GetSingle(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); + } + toolsOverride = array; continue; } - if (property.NameEquals("stream"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - stream = null; continue; } - stream = property.Value.GetBoolean(); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("max_prompt_tokens"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - maxPromptTokens = null; + temperature = null; continue; } - maxPromptTokens = property.Value.GetInt32(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("max_completion_tokens"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - maxCompletionTokens = null; + nucleusSamplingFactor = null; continue; } - maxCompletionTokens = property.Value.GetInt32(); + nucleusSamplingFactor = prop.Value.GetSingle(); continue; } - if (property.NameEquals("truncation_strategy"u8)) + if (prop.NameEquals("max_prompt_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - truncationStrategy = null; + maxInputTokenCount = null; continue; } - truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(property.Value, options); + maxInputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("max_completion_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolChoice = null; + maxOutputTokenCount = null; continue; } - toolChoice = Assistants.ToolConstraint.DeserializeToolConstraint(property.Value, options); + maxOutputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("parallel_tool_calls"u8)) + if (prop.NameEquals("truncation_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + truncationStrategy = null; continue; } - parallelToolCalls = property.Value.GetBoolean(); + truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(prop.Value, options); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("tool_choice"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + toolConstraint = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + toolConstraint = ToolConstraint.DeserializeToolConstraint(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new RunCreationOptions( assistantId, - model, - instructions, + stream, + responseFormat, + modelOverride, + instructionsOverride, additionalInstructions, - additionalMessages ?? new ChangeTrackingList(), - tools ?? new ChangeTrackingList(), + internalMessages ?? new ChangeTrackingList(), + allowParallelToolCalls, + toolsOverride ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), temperature, - topP, - stream, - maxPromptTokens, - maxCompletionTokens, + nucleusSamplingFactor, + maxInputTokenCount, + maxOutputTokenCount, truncationStrategy, - toolChoice, - parallelToolCalls, - responseFormat, - serializedAdditionalRawData); + toolConstraint, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -483,15 +497,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - RunCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunCreationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunCreationOptions(document.RootElement, options); } default: @@ -501,15 +516,20 @@ RunCreationOptions IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunCreationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunCreationOptions runCreationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunCreationOptions(document.RootElement); + if (runCreationOptions == null) + { + return null; + } + return BinaryContent.Create(runCreationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunCreationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunCreationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunCreationOptions.cs b/src/Generated/Models/RunCreationOptions.cs index d0cc33305..a25c920fc 100644 --- a/src/Generated/Models/RunCreationOptions.cs +++ b/src/Generated/Models/RunCreationOptions.cs @@ -9,27 +9,33 @@ namespace OpenAI.Assistants { public partial class RunCreationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal RunCreationOptions(string assistantId, string modelOverride, string instructionsOverride, string additionalInstructions, IList internalMessages, IList toolsOverride, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, bool? stream, int? maxInputTokenCount, int? maxOutputTokenCount, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal RunCreationOptions(string assistantId, bool? stream, AssistantResponseFormat responseFormat, string modelOverride, string instructionsOverride, string additionalInstructions, IList internalMessages, bool? allowParallelToolCalls, IList toolsOverride, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, int? maxInputTokenCount, int? maxOutputTokenCount, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, IDictionary additionalBinaryDataProperties) { AssistantId = assistantId; + Stream = stream; + ResponseFormat = responseFormat; ModelOverride = modelOverride; InstructionsOverride = instructionsOverride; AdditionalInstructions = additionalInstructions; InternalMessages = internalMessages; + AllowParallelToolCalls = allowParallelToolCalls; ToolsOverride = toolsOverride; Metadata = metadata; Temperature = temperature; NucleusSamplingFactor = nucleusSamplingFactor; - Stream = stream; MaxInputTokenCount = maxInputTokenCount; MaxOutputTokenCount = maxOutputTokenCount; TruncationStrategy = truncationStrategy; ToolConstraint = toolConstraint; - AllowParallelToolCalls = allowParallelToolCalls; - ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/RunError.Serialization.cs b/src/Generated/Models/RunError.Serialization.cs index df0a592e1..2075c5e8d 100644 --- a/src/Generated/Models/RunError.Serialization.cs +++ b/src/Generated/Models/RunError.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunError : IJsonModel { + internal RunError() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) + if (_additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions #endif } } - writer.WriteEndObject(); } - RunError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunError(document.RootElement, options); } - internal static RunError DeserializeRunError(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunError DeserializeRunError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } RunErrorCode code = default; string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = new RunErrorCode(property.Value.GetString()); + code = new RunErrorCode(prop.Value.GetString()); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunError(code, message, serializedAdditionalRawData); + return new RunError(code, message, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - RunError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunError(document.RootElement, options); } default: @@ -130,15 +137,20 @@ RunError IPersistableModel.Create(BinaryData data, ModelReaderWriterOp string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunError runError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunError(document.RootElement); + if (runError == null) + { + return null; + } + return BinaryContent.Create(runError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunError.cs b/src/Generated/Models/RunError.cs index 8404fbbe2..f769954e0 100644 --- a/src/Generated/Models/RunError.cs +++ b/src/Generated/Models/RunError.cs @@ -9,27 +9,29 @@ namespace OpenAI.Assistants { public partial class RunError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunError(RunErrorCode code, string message) { - Argument.AssertNotNull(message, nameof(message)); - Code = code; Message = message; } - internal RunError(RunErrorCode code, string message, IDictionary serializedAdditionalRawData) + internal RunError(RunErrorCode code, string message, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal RunError() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public RunErrorCode Code { get; } + public string Message { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunErrorCode.cs b/src/Generated/Models/RunErrorCode.cs index 815942d5e..faa82cd51 100644 --- a/src/Generated/Models/RunErrorCode.cs +++ b/src/Generated/Models/RunErrorCode.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunErrorCode : IEquatable { private readonly string _value; + private const string ServerErrorValue = "server_error"; + private const string RateLimitExceededValue = "rate_limit_exceeded"; + private const string InvalidPromptValue = "invalid_prompt"; public RunErrorCode(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ServerErrorValue = "server_error"; - private const string RateLimitExceededValue = "rate_limit_exceeded"; - private const string InvalidPromptValue = "invalid_prompt"; + _value = value; + } public static RunErrorCode ServerError { get; } = new RunErrorCode(ServerErrorValue); + public static RunErrorCode RateLimitExceeded { get; } = new RunErrorCode(RateLimitExceededValue); + public static RunErrorCode InvalidPrompt { get; } = new RunErrorCode(InvalidPromptValue); + public static bool operator ==(RunErrorCode left, RunErrorCode right) => left.Equals(right); + public static bool operator !=(RunErrorCode left, RunErrorCode right) => !left.Equals(right); + public static implicit operator RunErrorCode(string value) => new RunErrorCode(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunErrorCode other && Equals(other); + public bool Equals(RunErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunIncompleteDetails.Serialization.cs b/src/Generated/Models/RunIncompleteDetails.Serialization.cs index 097376a17..a051dfbe6 100644 --- a/src/Generated/Models/RunIncompleteDetails.Serialization.cs +++ b/src/Generated/Models/RunIncompleteDetails.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,21 +15,26 @@ public partial class RunIncompleteDetails : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunIncompleteDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("reason") != true && Optional.IsDefined(Reason)) + if (Optional.IsDefined(Reason) && _additionalBinaryDataProperties?.ContainsKey("reason") != true) { writer.WritePropertyName("reason"u8); writer.WriteStringValue(Reason.Value.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +42,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,57 +51,53 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr #endif } } - writer.WriteEndObject(); } - RunIncompleteDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunIncompleteDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunIncompleteDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunIncompleteDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunIncompleteDetails(document.RootElement, options); } - internal static RunIncompleteDetails DeserializeRunIncompleteDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunIncompleteDetails DeserializeRunIncompleteDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } RunIncompleteReason? reason = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("reason"u8)) + if (prop.NameEquals("reason"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - reason = new RunIncompleteReason(property.Value.GetString()); + reason = new RunIncompleteReason(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunIncompleteDetails(reason, serializedAdditionalRawData); + return new RunIncompleteDetails(reason, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -105,15 +107,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - RunIncompleteDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunIncompleteDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunIncompleteDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunIncompleteDetails(document.RootElement, options); } default: @@ -123,15 +126,20 @@ RunIncompleteDetails IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunIncompleteDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunIncompleteDetails runIncompleteDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunIncompleteDetails(document.RootElement); + if (runIncompleteDetails == null) + { + return null; + } + return BinaryContent.Create(runIncompleteDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunIncompleteDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunIncompleteDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunIncompleteDetails.cs b/src/Generated/Models/RunIncompleteDetails.cs index 5c063d7c0..cd853f37a 100644 --- a/src/Generated/Models/RunIncompleteDetails.cs +++ b/src/Generated/Models/RunIncompleteDetails.cs @@ -9,17 +9,24 @@ namespace OpenAI.Assistants { public partial class RunIncompleteDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunIncompleteDetails() { } - internal RunIncompleteDetails(RunIncompleteReason? reason, IDictionary serializedAdditionalRawData) + internal RunIncompleteDetails(RunIncompleteReason? reason, IDictionary additionalBinaryDataProperties) { Reason = reason; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public RunIncompleteReason? Reason { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunIncompleteReason.cs b/src/Generated/Models/RunIncompleteReason.cs index 28cdbd676..514d5b257 100644 --- a/src/Generated/Models/RunIncompleteReason.cs +++ b/src/Generated/Models/RunIncompleteReason.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunIncompleteReason : IEquatable { private readonly string _value; + private const string MaxCompletionTokensValue = "max_completion_tokens"; + private const string MaxPromptTokensValue = "max_prompt_tokens"; public RunIncompleteReason(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string MaxOutputTokenCountValue = "max_completion_tokens"; - private const string MaxInputTokenCountValue = "max_prompt_tokens"; public static bool operator ==(RunIncompleteReason left, RunIncompleteReason right) => left.Equals(right); + public static bool operator !=(RunIncompleteReason left, RunIncompleteReason right) => !left.Equals(right); + public static implicit operator RunIncompleteReason(string value) => new RunIncompleteReason(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunIncompleteReason other && Equals(other); + public bool Equals(RunIncompleteReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunModificationOptions.Serialization.cs b/src/Generated/Models/RunModificationOptions.Serialization.cs index f13f9b1a8..a5fbcc544 100644 --- a/src/Generated/Models/RunModificationOptions.Serialization.cs +++ b/src/Generated/Models/RunModificationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,14 +15,19 @@ public partial class RunModificationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunModificationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -30,18 +36,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -49,7 +60,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -58,62 +69,65 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader #endif } } - writer.WriteEndObject(); } - RunModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunModificationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunModificationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunModificationOptions(document.RootElement, options); } - internal static RunModificationOptions DeserializeRunModificationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunModificationOptions DeserializeRunModificationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunModificationOptions(metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new RunModificationOptions(metadata ?? new ChangeTrackingDictionary(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +137,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpti } } - RunModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunModificationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunModificationOptions(document.RootElement, options); } default: @@ -141,15 +156,20 @@ RunModificationOptions IPersistableModel.Create(BinaryDa string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunModificationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunModificationOptions runModificationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunModificationOptions(document.RootElement); + if (runModificationOptions == null) + { + return null; + } + return BinaryContent.Create(runModificationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunModificationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunModificationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunModificationOptions.cs b/src/Generated/Models/RunModificationOptions.cs index b9c29be48..4295bfb3f 100644 --- a/src/Generated/Models/RunModificationOptions.cs +++ b/src/Generated/Models/RunModificationOptions.cs @@ -4,23 +4,31 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class RunModificationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public RunModificationOptions() { Metadata = new ChangeTrackingDictionary(); } - internal RunModificationOptions(IDictionary metadata, IDictionary serializedAdditionalRawData) + internal RunModificationOptions(IDictionary metadata, IDictionary additionalBinaryDataProperties) { Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStatus.cs b/src/Generated/Models/RunStatus.cs index 08c6af672..714824f53 100644 --- a/src/Generated/Models/RunStatus.cs +++ b/src/Generated/Models/RunStatus.cs @@ -4,18 +4,13 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunStatus : IEquatable { private readonly string _value; - - public RunStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string QueuedValue = "queued"; private const string InProgressValue = "in_progress"; private const string RequiresActionValue = "requires_action"; @@ -26,25 +21,45 @@ public RunStatus(string value) private const string IncompleteValue = "incomplete"; private const string ExpiredValue = "expired"; + public RunStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static RunStatus Queued { get; } = new RunStatus(QueuedValue); + public static RunStatus InProgress { get; } = new RunStatus(InProgressValue); + public static RunStatus RequiresAction { get; } = new RunStatus(RequiresActionValue); + public static RunStatus Cancelling { get; } = new RunStatus(CancellingValue); + public static RunStatus Cancelled { get; } = new RunStatus(CancelledValue); + public static RunStatus Failed { get; } = new RunStatus(FailedValue); + public static RunStatus Completed { get; } = new RunStatus(CompletedValue); + public static RunStatus Incomplete { get; } = new RunStatus(IncompleteValue); + public static RunStatus Expired { get; } = new RunStatus(ExpiredValue); + public static bool operator ==(RunStatus left, RunStatus right) => left.Equals(right); + public static bool operator !=(RunStatus left, RunStatus right) => !left.Equals(right); + public static implicit operator RunStatus(string value) => new RunStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunStatus other && Equals(other); + public bool Equals(RunStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunStep.Serialization.cs b/src/Generated/Models/RunStep.Serialization.cs index 05bf9ecfe..f23a7ef63 100644 --- a/src/Generated/Models/RunStep.Serialization.cs +++ b/src/Generated/Models/RunStep.Serialization.cs @@ -7,66 +7,61 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStep : IJsonModel { + internal RunStep() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStep)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("assistant_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (SerializedAdditionalRawData?.ContainsKey("thread_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("thread_id") != true) { writer.WritePropertyName("thread_id"u8); writer.WriteStringValue(ThreadId); } - if (SerializedAdditionalRawData?.ContainsKey("run_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("run_id") != true) { writer.WritePropertyName("run_id"u8); writer.WriteStringValue(RunId); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("step_details") != true) - { - writer.WritePropertyName("step_details"u8); - writer.WriteObjectValue(Details, options); - } - if (SerializedAdditionalRawData?.ContainsKey("last_error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_error") != true) { if (LastError != null) { @@ -75,10 +70,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("last_error"); + writer.WriteNull("lastError"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("expired_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("expired_at") != true) { if (ExpiredAt != null) { @@ -87,10 +82,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("expired_at"); + writer.WriteNull("expiredAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("cancelled_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cancelled_at") != true) { if (CancelledAt != null) { @@ -99,10 +94,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("cancelled_at"); + writer.WriteNull("cancelledAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("failed_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("failed_at") != true) { if (FailedAt != null) { @@ -111,10 +106,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("failed_at"); + writer.WriteNull("failedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("completed_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed_at") != true) { if (CompletedAt != null) { @@ -123,10 +118,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("completed_at"); + writer.WriteNull("completedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { @@ -135,16 +130,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true) + if (_additionalBinaryDataProperties?.ContainsKey("usage") != true) { if (Usage != null) { @@ -153,12 +153,27 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } else { - writer.WriteNull("usage"); + writer.WriteNull("usage"u8); } } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("step_details") != true) + { + writer.WritePropertyName("step_details"u8); + writer.WriteObjectValue(Details, options); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -166,7 +181,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -175,38 +190,33 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o #endif } } - writer.WriteEndObject(); } - RunStep IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStep IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStep JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStep)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStep(document.RootElement, options); } - internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalRunStepObjectObject @object = default; DateTimeOffset createdAt = default; string assistantId = default; string threadId = default; string runId = default; - RunStepKind type = default; RunStepStatus status = default; - RunStepDetails stepDetails = default; RunStepError lastError = default; DateTimeOffset? expiredAt = default; DateTimeOffset? cancelledAt = default; @@ -214,147 +224,151 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite DateTimeOffset? completedAt = default; IReadOnlyDictionary metadata = default; RunStepTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalRunStepObjectObject @object = default; + Assistants.RunStepKind kind = default; + RunStepDetails details = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalRunStepObjectObject(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("assistant_id"u8)) + if (prop.NameEquals("assistant_id"u8)) { - assistantId = property.Value.GetString(); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("thread_id"u8)) + if (prop.NameEquals("thread_id"u8)) { - threadId = property.Value.GetString(); + threadId = prop.Value.GetString(); continue; } - if (property.NameEquals("run_id"u8)) + if (prop.NameEquals("run_id"u8)) { - runId = property.Value.GetString(); + runId = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("status"u8)) { - type = property.Value.GetString().ToRunStepKind(); + status = new RunStepStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("last_error"u8)) { - status = new RunStepStatus(property.Value.GetString()); - continue; - } - if (property.NameEquals("step_details"u8)) - { - stepDetails = RunStepDetails.DeserializeRunStepDetails(property.Value, options); - continue; - } - if (property.NameEquals("last_error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { lastError = null; continue; } - lastError = RunStepError.DeserializeRunStepError(property.Value, options); + lastError = RunStepError.DeserializeRunStepError(prop.Value, options); continue; } - if (property.NameEquals("expired_at"u8)) + if (prop.NameEquals("expired_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { expiredAt = null; continue; } - expiredAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiredAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("cancelled_at"u8)) + if (prop.NameEquals("cancelled_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { cancelledAt = null; continue; } - cancelledAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + cancelledAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("failed_at"u8)) + if (prop.NameEquals("failed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { failedAt = null; continue; } - failedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + failedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("completed_at"u8)) + if (prop.NameEquals("completed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { completedAt = null; continue; } - completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { metadata = new ChangeTrackingDictionary(); continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { usage = null; continue; } - usage = RunStepTokenUsage.DeserializeRunStepTokenUsage(property.Value, options); + usage = RunStepTokenUsage.DeserializeRunStepTokenUsage(prop.Value, options); + continue; + } + if (prop.NameEquals("object"u8)) + { + @object = new InternalRunStepObjectObject(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("type"u8)) + { + kind = prop.Value.GetString().ToRunStepKind(); + continue; + } + if (prop.NameEquals("step_details"u8)) + { + details = RunStepDetails.DeserializeRunStepDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new RunStep( id, - @object, createdAt, assistantId, threadId, runId, - type, status, - stepDetails, lastError, expiredAt, cancelledAt, @@ -362,13 +376,17 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite completedAt, metadata, usage, - serializedAdditionalRawData); + @object, + kind, + details, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -378,15 +396,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - RunStep IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStep IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStep 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStep(document.RootElement, options); } default: @@ -396,15 +415,20 @@ RunStep IPersistableModel.Create(BinaryData data, ModelReaderWriterOpti string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStep FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStep runStep) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStep(document.RootElement); + if (runStep == null) + { + return null; + } + return BinaryContent.Create(runStep, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStep(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStep(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStep.cs b/src/Generated/Models/RunStep.cs index 95efddeff..017ba1e29 100644 --- a/src/Generated/Models/RunStep.cs +++ b/src/Generated/Models/RunStep.cs @@ -4,48 +4,41 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStep { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal RunStep(string id, DateTimeOffset createdAt, string assistantId, string threadId, string runId, RunStepKind kind, RunStepStatus status, RunStepDetails details, RunStepError lastError, DateTimeOffset? expiredAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, IReadOnlyDictionary metadata, RunStepTokenUsage usage) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(assistantId, nameof(assistantId)); - Argument.AssertNotNull(threadId, nameof(threadId)); - Argument.AssertNotNull(runId, nameof(runId)); - Argument.AssertNotNull(details, nameof(details)); + private protected IDictionary _additionalBinaryDataProperties; + internal RunStep(string id, DateTimeOffset createdAt, string assistantId, string threadId, string runId, RunStepStatus status, RunStepError lastError, DateTimeOffset? expiredAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunStepTokenUsage usage, Assistants.RunStepKind kind, RunStepDetails details) + { Id = id; CreatedAt = createdAt; AssistantId = assistantId; ThreadId = threadId; RunId = runId; - Kind = kind; Status = status; - Details = details; LastError = lastError; ExpiredAt = expiredAt; CancelledAt = cancelledAt; FailedAt = failedAt; CompletedAt = completedAt; - Metadata = metadata; + Metadata = new ChangeTrackingDictionary(); Usage = usage; + Kind = kind; + Details = details; } - internal RunStep(string id, InternalRunStepObjectObject @object, DateTimeOffset createdAt, string assistantId, string threadId, string runId, RunStepKind kind, RunStepStatus status, RunStepDetails details, RunStepError lastError, DateTimeOffset? expiredAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, IReadOnlyDictionary metadata, RunStepTokenUsage usage, IDictionary serializedAdditionalRawData) + internal RunStep(string id, DateTimeOffset createdAt, string assistantId, string threadId, string runId, RunStepStatus status, RunStepError lastError, DateTimeOffset? expiredAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, IReadOnlyDictionary metadata, RunStepTokenUsage usage, InternalRunStepObjectObject @object, Assistants.RunStepKind kind, RunStepDetails details, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; CreatedAt = createdAt; AssistantId = assistantId; ThreadId = threadId; RunId = runId; - Kind = kind; Status = status; - Details = details; LastError = lastError; ExpiredAt = expiredAt; CancelledAt = cancelledAt; @@ -53,26 +46,42 @@ internal RunStep(string id, InternalRunStepObjectObject @object, DateTimeOffset CompletedAt = completedAt; Metadata = metadata; Usage = usage; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal RunStep() - { + this.Object = @object; + Kind = kind; + Details = details; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public string AssistantId { get; } + public string ThreadId { get; } + public string RunId { get; } + public RunStepStatus Status { get; } + public RunStepError LastError { get; } + public DateTimeOffset? ExpiredAt { get; } + public DateTimeOffset? CancelledAt { get; } + public DateTimeOffset? FailedAt { get; } + public DateTimeOffset? CompletedAt { get; } + public IReadOnlyDictionary Metadata { get; } + public RunStepTokenUsage Usage { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepCodeInterpreterOutput.Serialization.cs b/src/Generated/Models/RunStepCodeInterpreterOutput.Serialization.cs index f7ef07662..e6c7642f7 100644 --- a/src/Generated/Models/RunStepCodeInterpreterOutput.Serialization.cs +++ b/src/Generated/Models/RunStepCodeInterpreterOutput.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject))] - public partial class RunStepCodeInterpreterOutput : IJsonModel + public abstract partial class RunStepCodeInterpreterOutput : IJsonModel { + internal RunStepCodeInterpreterOutput() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepCodeInterpreterOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model #endif } } - writer.WriteEndObject(); } - RunStepCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepCodeInterpreterOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepCodeInterpreterOutput(document.RootElement, options); } - internal static RunStepCodeInterpreterOutput DeserializeRunStepCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepCodeInterpreterOutput DeserializeRunStepCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "image": return InternalRunStepDetailsToolCallsCodeOutputImageObject.DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(element, options); - case "logs": return InternalRunStepCodeInterpreterLogOutput.DeserializeInternalRunStepCodeInterpreterLogOutput(element, options); + case "logs": + return InternalRunStepCodeInterpreterLogOutput.DeserializeInternalRunStepCodeInterpreterLogOutput(element, options); + case "image": + return InternalRunStepDetailsToolCallsCodeOutputImageObject.DeserializeInternalRunStepDetailsToolCallsCodeOutputImageObject(element, options); } } return UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.DeserializeUnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - RunStepCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepCodeInterpreterOutput(document.RootElement, options); } default: @@ -110,15 +122,20 @@ RunStepCodeInterpreterOutput IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepCodeInterpreterOutput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepCodeInterpreterOutput runStepCodeInterpreterOutput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepCodeInterpreterOutput(document.RootElement); + if (runStepCodeInterpreterOutput == null) + { + return null; + } + return BinaryContent.Create(runStepCodeInterpreterOutput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepCodeInterpreterOutput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepCodeInterpreterOutput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepCodeInterpreterOutput.cs b/src/Generated/Models/RunStepCodeInterpreterOutput.cs index 1419ce55c..742f4c6f3 100644 --- a/src/Generated/Models/RunStepCodeInterpreterOutput.cs +++ b/src/Generated/Models/RunStepCodeInterpreterOutput.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { public abstract partial class RunStepCodeInterpreterOutput { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected RunStepCodeInterpreterOutput() + private protected IDictionary _additionalBinaryDataProperties; + + private protected RunStepCodeInterpreterOutput(string @type) { + Type = @type; } - internal RunStepCodeInterpreterOutput(string type, IDictionary serializedAdditionalRawData) + internal RunStepCodeInterpreterOutput(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepCollectionOrder.cs b/src/Generated/Models/RunStepCollectionOrder.cs index a818d310b..ec2f727c4 100644 --- a/src/Generated/Models/RunStepCollectionOrder.cs +++ b/src/Generated/Models/RunStepCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunStepCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public RunStepCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(RunStepCollectionOrder left, RunStepCollectionOrder right) => left.Equals(right); + public static bool operator !=(RunStepCollectionOrder left, RunStepCollectionOrder right) => !left.Equals(right); + public static implicit operator RunStepCollectionOrder(string value) => new RunStepCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunStepCollectionOrder other && Equals(other); + public bool Equals(RunStepCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunStepDetails.Serialization.cs b/src/Generated/Models/RunStepDetails.Serialization.cs index 35e15ea14..dc51e99f1 100644 --- a/src/Generated/Models/RunStepDetails.Serialization.cs +++ b/src/Generated/Models/RunStepDetails.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepObjectStepDetails))] - public partial class RunStepDetails : IJsonModel + public abstract partial class RunStepDetails : IJsonModel { + internal RunStepDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp #endif } } - writer.WriteEndObject(); } - RunStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepDetails(document.RootElement, options); } - internal static RunStepDetails DeserializeRunStepDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepDetails DeserializeRunStepDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "message_creation": return InternalRunStepDetailsMessageCreationObject.DeserializeInternalRunStepDetailsMessageCreationObject(element, options); - case "tool_calls": return InternalRunStepDetailsToolCallsObject.DeserializeInternalRunStepDetailsToolCallsObject(element, options); + case "message_creation": + return InternalRunStepDetailsMessageCreationObject.DeserializeInternalRunStepDetailsMessageCreationObject(element, options); + case "tool_calls": + return InternalRunStepDetailsToolCallsObject.DeserializeInternalRunStepDetailsToolCallsObject(element, options); } } return UnknownRunStepObjectStepDetails.DeserializeUnknownRunStepObjectStepDetails(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - RunStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepDetails(document.RootElement, options); } default: @@ -110,15 +122,20 @@ RunStepDetails IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepDetails FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepDetails runStepDetails) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepDetails(document.RootElement); + if (runStepDetails == null) + { + return null; + } + return BinaryContent.Create(runStepDetails, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepDetails(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDetails(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepDetails.cs b/src/Generated/Models/RunStepDetails.cs index 29a98a672..fef8ce678 100644 --- a/src/Generated/Models/RunStepDetails.cs +++ b/src/Generated/Models/RunStepDetails.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { public abstract partial class RunStepDetails { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected RunStepDetails() + private protected IDictionary _additionalBinaryDataProperties; + + private protected RunStepDetails(string @type) { + Type = @type; } - internal RunStepDetails(string type, IDictionary serializedAdditionalRawData) + internal RunStepDetails(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepError.Serialization.cs b/src/Generated/Models/RunStepError.Serialization.cs index 2e84d4c87..dedc4b148 100644 --- a/src/Generated/Models/RunStepError.Serialization.cs +++ b/src/Generated/Models/RunStepError.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStepError : IJsonModel { + internal RunStepError() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) + if (_additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti #endif } } - writer.WriteEndObject(); } - RunStepError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepError(document.RootElement, options); } - internal static RunStepError DeserializeRunStepError(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepError DeserializeRunStepError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } RunStepErrorCode code = default; string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = new RunStepErrorCode(property.Value.GetString()); + code = new RunStepErrorCode(prop.Value.GetString()); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunStepError(code, message, serializedAdditionalRawData); + return new RunStepError(code, message, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions option } } - RunStepError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepError(document.RootElement, options); } default: @@ -130,15 +137,20 @@ RunStepError IPersistableModel.Create(BinaryData data, ModelReader string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepError runStepError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepError(document.RootElement); + if (runStepError == null) + { + return null; + } + return BinaryContent.Create(runStepError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepError.cs b/src/Generated/Models/RunStepError.cs index 780003cbb..bcc513242 100644 --- a/src/Generated/Models/RunStepError.cs +++ b/src/Generated/Models/RunStepError.cs @@ -9,27 +9,29 @@ namespace OpenAI.Assistants { public partial class RunStepError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunStepError(RunStepErrorCode code, string message) { - Argument.AssertNotNull(message, nameof(message)); - Code = code; Message = message; } - internal RunStepError(RunStepErrorCode code, string message, IDictionary serializedAdditionalRawData) + internal RunStepError(RunStepErrorCode code, string message, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal RunStepError() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public RunStepErrorCode Code { get; } + public string Message { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepErrorCode.cs b/src/Generated/Models/RunStepErrorCode.cs index 3feed9ad8..853f910e5 100644 --- a/src/Generated/Models/RunStepErrorCode.cs +++ b/src/Generated/Models/RunStepErrorCode.cs @@ -4,33 +4,41 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunStepErrorCode : IEquatable { private readonly string _value; + private const string ServerErrorValue = "server_error"; + private const string RateLimitExceededValue = "rate_limit_exceeded"; public RunStepErrorCode(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ServerErrorValue = "server_error"; - private const string RateLimitExceededValue = "rate_limit_exceeded"; + _value = value; + } public static RunStepErrorCode ServerError { get; } = new RunStepErrorCode(ServerErrorValue); + public static RunStepErrorCode RateLimitExceeded { get; } = new RunStepErrorCode(RateLimitExceededValue); + public static bool operator ==(RunStepErrorCode left, RunStepErrorCode right) => left.Equals(right); + public static bool operator !=(RunStepErrorCode left, RunStepErrorCode right) => !left.Equals(right); + public static implicit operator RunStepErrorCode(string value) => new RunStepErrorCode(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunStepErrorCode other && Equals(other); + public bool Equals(RunStepErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunStepFileSearchResult.Serialization.cs b/src/Generated/Models/RunStepFileSearchResult.Serialization.cs index fe9bb6d81..9d77a2d41 100644 --- a/src/Generated/Models/RunStepFileSearchResult.Serialization.cs +++ b/src/Generated/Models/RunStepFileSearchResult.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStepFileSearchResult : IJsonModel { + internal RunStepFileSearchResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepFileSearchResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_id") != true) { writer.WritePropertyName("file_id"u8); writer.WriteStringValue(FileId); } - if (SerializedAdditionalRawData?.ContainsKey("file_name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_name") != true) { writer.WritePropertyName("file_name"u8); writer.WriteStringValue(FileName); } - if (SerializedAdditionalRawData?.ContainsKey("score") != true) + if (_additionalBinaryDataProperties?.ContainsKey("score") != true) { writer.WritePropertyName("score"u8); writer.WriteNumberValue(Score); } - if (SerializedAdditionalRawData?.ContainsKey("content") != true && Optional.IsCollectionDefined(Content)) + if (true && Optional.IsCollectionDefined(Content) && _additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (RunStepFileSearchResultContent item in Content) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,25 +75,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - RunStepFileSearchResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepFileSearchResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepFileSearchResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepFileSearchResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepFileSearchResult(document.RootElement, options); } - internal static RunStepFileSearchResult DeserializeRunStepFileSearchResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepFileSearchResult DeserializeRunStepFileSearchResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -92,33 +100,32 @@ internal static RunStepFileSearchResult DeserializeRunStepFileSearchResult(JsonE string fileName = default; float score = default; IReadOnlyList content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (prop.NameEquals("file_id"u8)) { - fileId = property.Value.GetString(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("file_name"u8)) + if (prop.NameEquals("file_name"u8)) { - fileName = property.Value.GetString(); + fileName = prop.Value.GetString(); continue; } - if (property.NameEquals("score"u8)) + if (prop.NameEquals("score"u8)) { - score = property.Value.GetSingle(); + score = prop.Value.GetSingle(); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("content"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(RunStepFileSearchResultContent.DeserializeRunStepFileSearchResultContent(item, options)); } @@ -127,18 +134,17 @@ internal static RunStepFileSearchResult DeserializeRunStepFileSearchResult(JsonE } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunStepFileSearchResult(fileId, fileName, score, content ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new RunStepFileSearchResult(fileId, fileName, score, content ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -148,15 +154,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - RunStepFileSearchResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepFileSearchResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepFileSearchResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepFileSearchResult(document.RootElement, options); } default: @@ -166,15 +173,20 @@ RunStepFileSearchResult IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepFileSearchResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepFileSearchResult runStepFileSearchResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepFileSearchResult(document.RootElement); + if (runStepFileSearchResult == null) + { + return null; + } + return BinaryContent.Create(runStepFileSearchResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepFileSearchResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepFileSearchResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepFileSearchResult.cs b/src/Generated/Models/RunStepFileSearchResult.cs index bcb29e280..eb446f12a 100644 --- a/src/Generated/Models/RunStepFileSearchResult.cs +++ b/src/Generated/Models/RunStepFileSearchResult.cs @@ -4,39 +4,43 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStepFileSearchResult { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunStepFileSearchResult(string fileId, string fileName, float score) { - Argument.AssertNotNull(fileId, nameof(fileId)); - Argument.AssertNotNull(fileName, nameof(fileName)); - FileId = fileId; FileName = fileName; Score = score; Content = new ChangeTrackingList(); } - internal RunStepFileSearchResult(string fileId, string fileName, float score, IReadOnlyList content, IDictionary serializedAdditionalRawData) + internal RunStepFileSearchResult(string fileId, string fileName, float score, IReadOnlyList content, IDictionary additionalBinaryDataProperties) { FileId = fileId; FileName = fileName; Score = score; Content = content; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal RunStepFileSearchResult() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string FileId { get; } + public string FileName { get; } + public float Score { get; } + public IReadOnlyList Content { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepFileSearchResultContent.Serialization.cs b/src/Generated/Models/RunStepFileSearchResultContent.Serialization.cs index 792c4ac0d..ff4b07f50 100644 --- a/src/Generated/Models/RunStepFileSearchResultContent.Serialization.cs +++ b/src/Generated/Models/RunStepFileSearchResultContent.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ public partial class RunStepFileSearchResultContent : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepFileSearchResultContent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("text") != true && Optional.IsDefined(Text)) + if (Optional.IsDefined(Text) && _additionalBinaryDataProperties?.ContainsKey("text") != true) { writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod #endif } } - writer.WriteEndObject(); } - RunStepFileSearchResultContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepFileSearchResultContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepFileSearchResultContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepFileSearchResultContent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepFileSearchResultContent(document.RootElement, options); } - internal static RunStepFileSearchResultContent DeserializeRunStepFileSearchResultContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepFileSearchResultContent DeserializeRunStepFileSearchResultContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - RunStepFileSearchResultContentKind type = default; string text = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.RunStepFileSearchResultContentKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("text"u8)) { - type = property.Value.GetString().ToRunStepFileSearchResultContentKind(); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("type"u8)) { - text = property.Value.GetString(); + kind = prop.Value.GetString().ToRunStepFileSearchResultContentKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunStepFileSearchResultContent(type, text, serializedAdditionalRawData); + return new RunStepFileSearchResultContent(text, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - RunStepFileSearchResultContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepFileSearchResultContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepFileSearchResultContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepFileSearchResultContent(document.RootElement, options); } default: @@ -130,15 +133,20 @@ RunStepFileSearchResultContent IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepFileSearchResultContent FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepFileSearchResultContent runStepFileSearchResultContent) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepFileSearchResultContent(document.RootElement); + if (runStepFileSearchResultContent == null) + { + return null; + } + return BinaryContent.Create(runStepFileSearchResultContent, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepFileSearchResultContent(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepFileSearchResultContent(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepFileSearchResultContent.cs b/src/Generated/Models/RunStepFileSearchResultContent.cs index d0e235797..95d299b19 100644 --- a/src/Generated/Models/RunStepFileSearchResultContent.cs +++ b/src/Generated/Models/RunStepFileSearchResultContent.cs @@ -9,18 +9,25 @@ namespace OpenAI.Assistants { public partial class RunStepFileSearchResultContent { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunStepFileSearchResultContent() { } - internal RunStepFileSearchResultContent(RunStepFileSearchResultContentKind kind, string text, IDictionary serializedAdditionalRawData) + internal RunStepFileSearchResultContent(string text, Assistants.RunStepFileSearchResultContentKind kind, IDictionary additionalBinaryDataProperties) { - Kind = kind; Text = text; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Text { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepFileSearchResultContentKind.Serialization.cs b/src/Generated/Models/RunStepFileSearchResultContentKind.Serialization.cs index 758e2d186..b78bfaa22 100644 --- a/src/Generated/Models/RunStepFileSearchResultContentKind.Serialization.cs +++ b/src/Generated/Models/RunStepFileSearchResultContentKind.Serialization.cs @@ -8,15 +8,18 @@ namespace OpenAI.Assistants { internal static partial class RunStepFileSearchResultContentKindExtensions { - public static string ToSerialString(this RunStepFileSearchResultContentKind value) => value switch + public static string ToSerialString(this Assistants.RunStepFileSearchResultContentKind value) => value switch { - RunStepFileSearchResultContentKind.Text => "text", + Assistants.RunStepFileSearchResultContentKind.Text => "text", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepFileSearchResultContentKind value.") }; - public static RunStepFileSearchResultContentKind ToRunStepFileSearchResultContentKind(this string value) + public static Assistants.RunStepFileSearchResultContentKind ToRunStepFileSearchResultContentKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "text")) return RunStepFileSearchResultContentKind.Text; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "text")) + { + return Assistants.RunStepFileSearchResultContentKind.Text; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepFileSearchResultContentKind value."); } } diff --git a/src/Generated/Models/RunStepKind.Serialization.cs b/src/Generated/Models/RunStepKind.Serialization.cs index 3ac4785f1..7372a1f0e 100644 --- a/src/Generated/Models/RunStepKind.Serialization.cs +++ b/src/Generated/Models/RunStepKind.Serialization.cs @@ -8,17 +8,23 @@ namespace OpenAI.Assistants { internal static partial class RunStepKindExtensions { - public static string ToSerialString(this RunStepKind value) => value switch + public static string ToSerialString(this Assistants.RunStepKind value) => value switch { - RunStepKind.CreatedMessage => "message_creation", - RunStepKind.ToolCall => "tool_calls", + Assistants.RunStepKind.CreatedMessage => "message_creation", + Assistants.RunStepKind.ToolCall => "tool_calls", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepKind value.") }; - public static RunStepKind ToRunStepKind(this string value) + public static Assistants.RunStepKind ToRunStepKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "message_creation")) return RunStepKind.CreatedMessage; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool_calls")) return RunStepKind.ToolCall; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "message_creation")) + { + return Assistants.RunStepKind.CreatedMessage; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "tool_calls")) + { + return Assistants.RunStepKind.ToolCall; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepKind value."); } } diff --git a/src/Generated/Models/RunStepStatus.cs b/src/Generated/Models/RunStepStatus.cs index b328305d0..fa5259ea2 100644 --- a/src/Generated/Models/RunStepStatus.cs +++ b/src/Generated/Models/RunStepStatus.cs @@ -4,39 +4,50 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.Assistants { public readonly partial struct RunStepStatus : IEquatable { private readonly string _value; - - public RunStepStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string InProgressValue = "in_progress"; private const string CancelledValue = "cancelled"; private const string FailedValue = "failed"; private const string CompletedValue = "completed"; private const string ExpiredValue = "expired"; + public RunStepStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static RunStepStatus InProgress { get; } = new RunStepStatus(InProgressValue); + public static RunStepStatus Cancelled { get; } = new RunStepStatus(CancelledValue); + public static RunStepStatus Failed { get; } = new RunStepStatus(FailedValue); + public static RunStepStatus Completed { get; } = new RunStepStatus(CompletedValue); + public static RunStepStatus Expired { get; } = new RunStepStatus(ExpiredValue); + public static bool operator ==(RunStepStatus left, RunStepStatus right) => left.Equals(right); + public static bool operator !=(RunStepStatus left, RunStepStatus right) => !left.Equals(right); + public static implicit operator RunStepStatus(string value) => new RunStepStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is RunStepStatus other && Equals(other); + public bool Equals(RunStepStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/RunStepTokenUsage.Serialization.cs b/src/Generated/Models/RunStepTokenUsage.Serialization.cs index e3d81cbd0..d6932bd3f 100644 --- a/src/Generated/Models/RunStepTokenUsage.Serialization.cs +++ b/src/Generated/Models/RunStepTokenUsage.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunStepTokenUsage : IJsonModel { + internal RunStepTokenUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepTokenUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("completion_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_tokens") != true) { writer.WritePropertyName("completion_tokens"u8); writer.WriteNumberValue(OutputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); writer.WriteNumberValue(InputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokenCount); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrite #endif } } - writer.WriteEndObject(); } - RunStepTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepTokenUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepTokenUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepTokenUsage(document.RootElement, options); } - internal static RunStepTokenUsage DeserializeRunStepTokenUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepTokenUsage DeserializeRunStepTokenUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int completionTokens = default; - int promptTokens = default; - int totalTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int outputTokenCount = default; + int inputTokenCount = default; + int totalTokenCount = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("completion_tokens"u8)) + if (prop.NameEquals("completion_tokens"u8)) { - completionTokens = property.Value.GetInt32(); + outputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("prompt_tokens"u8)) + if (prop.NameEquals("prompt_tokens"u8)) { - promptTokens = property.Value.GetInt32(); + inputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokenCount = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunStepTokenUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + return new RunStepTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions o } } - RunStepTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepTokenUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepTokenUsage(document.RootElement, options); } default: @@ -141,15 +148,20 @@ RunStepTokenUsage IPersistableModel.Create(BinaryData data, M string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepTokenUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepTokenUsage runStepTokenUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepTokenUsage(document.RootElement); + if (runStepTokenUsage == null) + { + return null; + } + return BinaryContent.Create(runStepTokenUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepTokenUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepTokenUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepTokenUsage.cs b/src/Generated/Models/RunStepTokenUsage.cs index 34e6768b7..64ae6e1b6 100644 --- a/src/Generated/Models/RunStepTokenUsage.cs +++ b/src/Generated/Models/RunStepTokenUsage.cs @@ -9,7 +9,8 @@ namespace OpenAI.Assistants { public partial class RunStepTokenUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunStepTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount) { OutputTokenCount = outputTokenCount; @@ -17,16 +18,18 @@ internal RunStepTokenUsage(int outputTokenCount, int inputTokenCount, int totalT TotalTokenCount = totalTokenCount; } - internal RunStepTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, IDictionary serializedAdditionalRawData) + internal RunStepTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, IDictionary additionalBinaryDataProperties) { OutputTokenCount = outputTokenCount; InputTokenCount = inputTokenCount; TotalTokenCount = totalTokenCount; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal RunStepTokenUsage() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/RunStepToolCall.Serialization.cs b/src/Generated/Models/RunStepToolCall.Serialization.cs index 94c80534d..f41610cd6 100644 --- a/src/Generated/Models/RunStepToolCall.Serialization.cs +++ b/src/Generated/Models/RunStepToolCall.Serialization.cs @@ -6,34 +6,40 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepDetailsToolCallsObjectToolCallsObject))] - public partial class RunStepToolCall : IJsonModel + public abstract partial class RunStepToolCall : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepToolCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Kind.ToSerialString()); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,45 +56,47 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO #endif } } - writer.WriteEndObject(); } - RunStepToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepToolCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepToolCall(document.RootElement, options); } - internal static RunStepToolCall DeserializeRunStepToolCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepToolCall DeserializeRunStepToolCall(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "code_interpreter": return InternalRunStepDetailsToolCallsCodeObject.DeserializeInternalRunStepDetailsToolCallsCodeObject(element, options); - case "file_search": return InternalRunStepDetailsToolCallsFileSearchObject.DeserializeInternalRunStepDetailsToolCallsFileSearchObject(element, options); - case "function": return InternalRunStepDetailsToolCallsFunctionObject.DeserializeInternalRunStepDetailsToolCallsFunctionObject(element, options); + case "code_interpreter": + return InternalRunStepDetailsToolCallsCodeObject.DeserializeInternalRunStepDetailsToolCallsCodeObject(element, options); + case "file_search": + return InternalRunStepDetailsToolCallsFileSearchObject.DeserializeInternalRunStepDetailsToolCallsFileSearchObject(element, options); + case "function": + return InternalRunStepDetailsToolCallsFunctionObject.DeserializeInternalRunStepDetailsToolCallsFunctionObject(element, options); } } return UnknownRunStepDetailsToolCallsObjectToolCallsObject.DeserializeUnknownRunStepDetailsToolCallsObjectToolCallsObject(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -98,15 +106,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - RunStepToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepToolCall(document.RootElement, options); } default: @@ -116,15 +125,20 @@ RunStepToolCall IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepToolCall FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepToolCall runStepToolCall) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepToolCall(document.RootElement); + if (runStepToolCall == null) + { + return null; + } + return BinaryContent.Create(runStepToolCall, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepToolCall(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepToolCall(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepToolCall.cs b/src/Generated/Models/RunStepToolCall.cs index ff0d02d64..a1ff98139 100644 --- a/src/Generated/Models/RunStepToolCall.cs +++ b/src/Generated/Models/RunStepToolCall.cs @@ -9,14 +9,27 @@ namespace OpenAI.Assistants { public abstract partial class RunStepToolCall { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal RunStepToolCall(RunStepToolCallKind kind, string id, IDictionary serializedAdditionalRawData) + private protected RunStepToolCall(string id, Assistants.RunStepToolCallKind kind) { + Id = id; Kind = kind; + } + + internal RunStepToolCall(string id, Assistants.RunStepToolCallKind kind, IDictionary additionalBinaryDataProperties) + { Id = id; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public string Id { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunStepToolCallKind.Serialization.cs b/src/Generated/Models/RunStepToolCallKind.Serialization.cs index a6b5ae464..cf4164a28 100644 --- a/src/Generated/Models/RunStepToolCallKind.Serialization.cs +++ b/src/Generated/Models/RunStepToolCallKind.Serialization.cs @@ -8,19 +8,28 @@ namespace OpenAI.Assistants { internal static partial class RunStepToolCallKindExtensions { - public static string ToSerialString(this RunStepToolCallKind value) => value switch + public static string ToSerialString(this Assistants.RunStepToolCallKind value) => value switch { - RunStepToolCallKind.CodeInterpreter => "code_interpreter", - RunStepToolCallKind.FileSearch => "file_search", - RunStepToolCallKind.Function => "function", + Assistants.RunStepToolCallKind.CodeInterpreter => "code_interpreter", + Assistants.RunStepToolCallKind.FileSearch => "file_search", + Assistants.RunStepToolCallKind.Function => "function", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepToolCallKind value.") }; - public static RunStepToolCallKind ToRunStepToolCallKind(this string value) + public static Assistants.RunStepToolCallKind ToRunStepToolCallKind(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "code_interpreter")) return RunStepToolCallKind.CodeInterpreter; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "file_search")) return RunStepToolCallKind.FileSearch; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) return RunStepToolCallKind.Function; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "code_interpreter")) + { + return Assistants.RunStepToolCallKind.CodeInterpreter; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "file_search")) + { + return Assistants.RunStepToolCallKind.FileSearch; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "function")) + { + return Assistants.RunStepToolCallKind.Function; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown RunStepToolCallKind value."); } } diff --git a/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.Serialization.cs b/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.Serialization.cs index 15407f30d..0e7fec323 100644 --- a/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.Serialization.cs +++ b/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.Serialization.cs @@ -6,29 +6,39 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject))] - public partial class RunStepUpdateCodeInterpreterOutput : IJsonModel + public abstract partial class RunStepUpdateCodeInterpreterOutput : IJsonModel { + internal RunStepUpdateCodeInterpreterOutput() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepUpdateCodeInterpreterOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -36,7 +46,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -45,44 +55,45 @@ void IJsonModel.Write(Utf8JsonWriter writer, #endif } } - writer.WriteEndObject(); } - RunStepUpdateCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepUpdateCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunStepUpdateCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepUpdateCodeInterpreterOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement, options); } - internal static RunStepUpdateCodeInterpreterOutput DeserializeRunStepUpdateCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepUpdateCodeInterpreterOutput DeserializeRunStepUpdateCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "image": return InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(element, options); - case "logs": return InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(element, options); + case "logs": + return InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject(element, options); + case "image": + return InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject.DeserializeInternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject(element, options); } } return UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.DeserializeUnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -92,15 +103,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - RunStepUpdateCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepUpdateCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunStepUpdateCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement, options); } default: @@ -110,15 +122,20 @@ RunStepUpdateCodeInterpreterOutput IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunStepUpdateCodeInterpreterOutput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunStepUpdateCodeInterpreterOutput runStepUpdateCodeInterpreterOutput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement); + if (runStepUpdateCodeInterpreterOutput == null) + { + return null; + } + return BinaryContent.Create(runStepUpdateCodeInterpreterOutput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunStepUpdateCodeInterpreterOutput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.cs b/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.cs index 637332102..a70737784 100644 --- a/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.cs +++ b/src/Generated/Models/RunStepUpdateCodeInterpreterOutput.cs @@ -9,17 +9,25 @@ namespace OpenAI.Assistants { public abstract partial class RunStepUpdateCodeInterpreterOutput { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected RunStepUpdateCodeInterpreterOutput() + private protected IDictionary _additionalBinaryDataProperties; + + private protected RunStepUpdateCodeInterpreterOutput(string @type) { + Type = @type; } - internal RunStepUpdateCodeInterpreterOutput(string type, IDictionary serializedAdditionalRawData) + internal RunStepUpdateCodeInterpreterOutput(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/RunTokenUsage.Serialization.cs b/src/Generated/Models/RunTokenUsage.Serialization.cs index bd60e19af..c0d0347cd 100644 --- a/src/Generated/Models/RunTokenUsage.Serialization.cs +++ b/src/Generated/Models/RunTokenUsage.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunTokenUsage : IJsonModel { + internal RunTokenUsage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunTokenUsage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("completion_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completion_tokens") != true) { writer.WritePropertyName("completion_tokens"u8); writer.WriteNumberValue(OutputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); writer.WriteNumberValue(InputTokenCount); } - if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); writer.WriteNumberValue(TotalTokenCount); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt #endif } } - writer.WriteEndObject(); } - RunTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunTokenUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunTokenUsage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunTokenUsage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunTokenUsage(document.RootElement, options); } - internal static RunTokenUsage DeserializeRunTokenUsage(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunTokenUsage DeserializeRunTokenUsage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - int completionTokens = default; - int promptTokens = default; - int totalTokens = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + int outputTokenCount = default; + int inputTokenCount = default; + int totalTokenCount = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("completion_tokens"u8)) + if (prop.NameEquals("completion_tokens"u8)) { - completionTokens = property.Value.GetInt32(); + outputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("prompt_tokens"u8)) + if (prop.NameEquals("prompt_tokens"u8)) { - promptTokens = property.Value.GetInt32(); + inputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total_tokens"u8)) + if (prop.NameEquals("total_tokens"u8)) { - totalTokens = property.Value.GetInt32(); + totalTokenCount = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunTokenUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + return new RunTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions optio } } - RunTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunTokenUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunTokenUsage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunTokenUsage(document.RootElement, options); } default: @@ -141,15 +148,20 @@ RunTokenUsage IPersistableModel.Create(BinaryData data, ModelRead string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunTokenUsage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunTokenUsage runTokenUsage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunTokenUsage(document.RootElement); + if (runTokenUsage == null) + { + return null; + } + return BinaryContent.Create(runTokenUsage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunTokenUsage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunTokenUsage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunTokenUsage.cs b/src/Generated/Models/RunTokenUsage.cs index fce729839..134f4a50f 100644 --- a/src/Generated/Models/RunTokenUsage.cs +++ b/src/Generated/Models/RunTokenUsage.cs @@ -9,7 +9,8 @@ namespace OpenAI.Assistants { public partial class RunTokenUsage { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount) { OutputTokenCount = outputTokenCount; @@ -17,16 +18,18 @@ internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalToken TotalTokenCount = totalTokenCount; } - internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, IDictionary serializedAdditionalRawData) + internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, IDictionary additionalBinaryDataProperties) { OutputTokenCount = outputTokenCount; InputTokenCount = inputTokenCount; TotalTokenCount = totalTokenCount; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal RunTokenUsage() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/RunTruncationStrategy.Serialization.cs b/src/Generated/Models/RunTruncationStrategy.Serialization.cs index 7aad14eb4..7a07b063d 100644 --- a/src/Generated/Models/RunTruncationStrategy.Serialization.cs +++ b/src/Generated/Models/RunTruncationStrategy.Serialization.cs @@ -7,26 +7,31 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class RunTruncationStrategy : IJsonModel { + internal RunTruncationStrategy() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunTruncationStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(_type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("last_messages") != true && Optional.IsDefined(LastMessages)) + if (Optional.IsDefined(LastMessages) && _additionalBinaryDataProperties?.ContainsKey("last_messages") != true) { if (LastMessages != null) { @@ -35,12 +40,17 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } else { - writer.WriteNull("last_messages"); + writer.WriteNull("lastMessages"u8); } } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_type.ToString()); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -48,7 +58,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -57,64 +67,60 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - RunTruncationStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunTruncationStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual RunTruncationStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunTruncationStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunTruncationStrategy(document.RootElement, options); } - internal static RunTruncationStrategy DeserializeRunTruncationStrategy(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunTruncationStrategy DeserializeRunTruncationStrategy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalTruncationObjectType type = default; int? lastMessages = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalTruncationObjectType @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("last_messages"u8)) { - type = new InternalTruncationObjectType(property.Value.GetString()); - continue; - } - if (property.NameEquals("last_messages"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { lastMessages = null; continue; } - lastMessages = property.Value.GetInt32(); + lastMessages = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("type"u8)) + { + @type = new InternalTruncationObjectType(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new RunTruncationStrategy(type, lastMessages, serializedAdditionalRawData); + return new RunTruncationStrategy(lastMessages, @type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -124,15 +130,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - RunTruncationStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunTruncationStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual RunTruncationStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunTruncationStrategy(document.RootElement, options); } default: @@ -142,15 +149,20 @@ RunTruncationStrategy IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static RunTruncationStrategy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(RunTruncationStrategy runTruncationStrategy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRunTruncationStrategy(document.RootElement); + if (runTruncationStrategy == null) + { + return null; + } + return BinaryContent.Create(runTruncationStrategy, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator RunTruncationStrategy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeRunTruncationStrategy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/RunTruncationStrategy.cs b/src/Generated/Models/RunTruncationStrategy.cs index 3fb0b2da8..39d09cb7a 100644 --- a/src/Generated/Models/RunTruncationStrategy.cs +++ b/src/Generated/Models/RunTruncationStrategy.cs @@ -9,15 +9,19 @@ namespace OpenAI.Assistants { public partial class RunTruncationStrategy { - internal RunTruncationStrategy(InternalTruncationObjectType type, int? lastMessages, IDictionary serializedAdditionalRawData) + private protected IDictionary _additionalBinaryDataProperties; + + internal RunTruncationStrategy(int? lastMessages, InternalTruncationObjectType @type, IDictionary additionalBinaryDataProperties) { - _type = type; LastMessages = lastMessages; - SerializedAdditionalRawData = serializedAdditionalRawData; + _type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal RunTruncationStrategy() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/SpeechGenerationOptions.Serialization.cs b/src/Generated/Models/SpeechGenerationOptions.Serialization.cs index 823b6165b..bf52744ba 100644 --- a/src/Generated/Models/SpeechGenerationOptions.Serialization.cs +++ b/src/Generated/Models/SpeechGenerationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { @@ -14,41 +15,46 @@ public partial class SpeechGenerationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(SpeechGenerationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (Optional.IsDefined(ResponseFormat) && _additionalBinaryDataProperties?.ContainsKey("response_format") != true) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("input") != true) + if (_additionalBinaryDataProperties?.ContainsKey("input") != true) { writer.WritePropertyName("input"u8); writer.WriteStringValue(Input); } - if (SerializedAdditionalRawData?.ContainsKey("voice") != true) + if (_additionalBinaryDataProperties?.ContainsKey("voice") != true) { writer.WritePropertyName("voice"u8); writer.WriteStringValue(Voice.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) - { - writer.WritePropertyName("response_format"u8); - writer.WriteStringValue(ResponseFormat.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("speed") != true && Optional.IsDefined(SpeedRatio)) + if (Optional.IsDefined(SpeedRatio) && _additionalBinaryDataProperties?.ContainsKey("speed") != true) { writer.WritePropertyName("speed"u8); writer.WriteNumberValue(SpeedRatio.Value); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +62,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,91 +71,87 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - SpeechGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + SpeechGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual SpeechGenerationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeSpeechGenerationOptions(document.RootElement, options); } - internal static SpeechGenerationOptions DeserializeSpeechGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static SpeechGenerationOptions DeserializeSpeechGenerationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + GeneratedSpeechFormat? responseFormat = default; InternalCreateSpeechRequestModel model = default; string input = default; GeneratedSpeechVoice voice = default; - GeneratedSpeechFormat? responseFormat = default; - float? speed = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + float? speedRatio = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("model"u8)) + if (prop.NameEquals("response_format"u8)) { - model = new InternalCreateSpeechRequestModel(property.Value.GetString()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new GeneratedSpeechFormat(prop.Value.GetString()); continue; } - if (property.NameEquals("input"u8)) + if (prop.NameEquals("model"u8)) { - input = property.Value.GetString(); + model = new InternalCreateSpeechRequestModel(prop.Value.GetString()); continue; } - if (property.NameEquals("voice"u8)) + if (prop.NameEquals("input"u8)) { - voice = new GeneratedSpeechVoice(property.Value.GetString()); + input = prop.Value.GetString(); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("voice"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - responseFormat = new GeneratedSpeechFormat(property.Value.GetString()); + voice = new GeneratedSpeechVoice(prop.Value.GetString()); continue; } - if (property.NameEquals("speed"u8)) + if (prop.NameEquals("speed"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - speed = property.Value.GetSingle(); + speedRatio = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new SpeechGenerationOptions( + responseFormat, model, input, voice, - responseFormat, - speed, - serializedAdditionalRawData); + speedRatio, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -159,15 +161,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - SpeechGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + SpeechGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual SpeechGenerationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeSpeechGenerationOptions(document.RootElement, options); } default: @@ -177,15 +180,20 @@ SpeechGenerationOptions IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static SpeechGenerationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(SpeechGenerationOptions speechGenerationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeSpeechGenerationOptions(document.RootElement); + if (speechGenerationOptions == null) + { + return null; + } + return BinaryContent.Create(speechGenerationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator SpeechGenerationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeSpeechGenerationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/SpeechGenerationOptions.cs b/src/Generated/Models/SpeechGenerationOptions.cs index 8ecda5dc0..e48d5cf02 100644 --- a/src/Generated/Models/SpeechGenerationOptions.cs +++ b/src/Generated/Models/SpeechGenerationOptions.cs @@ -9,17 +9,24 @@ namespace OpenAI.Audio { public partial class SpeechGenerationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal SpeechGenerationOptions(InternalCreateSpeechRequestModel model, string input, GeneratedSpeechVoice voice, GeneratedSpeechFormat? responseFormat, float? speedRatio, IDictionary serializedAdditionalRawData) + internal SpeechGenerationOptions(GeneratedSpeechFormat? responseFormat, InternalCreateSpeechRequestModel model, string input, GeneratedSpeechVoice voice, float? speedRatio, IDictionary additionalBinaryDataProperties) { + ResponseFormat = responseFormat; Model = model; Input = input; Voice = voice; - ResponseFormat = responseFormat; SpeedRatio = speedRatio; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public GeneratedSpeechFormat? ResponseFormat { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/StaticFileChunkingStrategy.Serialization.cs b/src/Generated/Models/StaticFileChunkingStrategy.Serialization.cs index 94b1916af..d480e4317 100644 --- a/src/Generated/Models/StaticFileChunkingStrategy.Serialization.cs +++ b/src/Generated/Models/StaticFileChunkingStrategy.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class StaticFileChunkingStrategy : IJsonModel { + internal StaticFileChunkingStrategy() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(StaticFileChunkingStrategy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("static") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("static") != true) { writer.WritePropertyName("static"u8); writer.WriteObjectValue(_internalDetails, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - StaticFileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + StaticFileChunkingStrategy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (StaticFileChunkingStrategy)JsonModelCreateCore(ref reader, options); + + protected override FileChunkingStrategy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(StaticFileChunkingStrategy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeStaticFileChunkingStrategy(document.RootElement, options); } - internal static StaticFileChunkingStrategy DeserializeStaticFileChunkingStrategy(JsonElement element, ModelReaderWriterOptions options = null) + internal static StaticFileChunkingStrategy DeserializeStaticFileChunkingStrategy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalStaticChunkingStrategyDetails @static = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "static"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + InternalStaticChunkingStrategyDetails internalDetails = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("static"u8)) + if (prop.NameEquals("type"u8)) { - @static = InternalStaticChunkingStrategyDetails.DeserializeInternalStaticChunkingStrategyDetails(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("static"u8)) { - type = property.Value.GetString(); + internalDetails = InternalStaticChunkingStrategyDetails.DeserializeInternalStaticChunkingStrategyDetails(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new StaticFileChunkingStrategy(type, serializedAdditionalRawData, @static); + return new StaticFileChunkingStrategy(@type, additionalBinaryDataProperties, internalDetails); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - StaticFileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + StaticFileChunkingStrategy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (StaticFileChunkingStrategy)PersistableModelCreateCore(data, options); + protected override FileChunkingStrategy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeStaticFileChunkingStrategy(document.RootElement, options); } default: @@ -130,15 +114,20 @@ StaticFileChunkingStrategy IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new StaticFileChunkingStrategy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(StaticFileChunkingStrategy staticFileChunkingStrategy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeStaticFileChunkingStrategy(document.RootElement); + if (staticFileChunkingStrategy == null) + { + return null; + } + return BinaryContent.Create(staticFileChunkingStrategy, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator StaticFileChunkingStrategy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeStaticFileChunkingStrategy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/StaticFileChunkingStrategy.cs b/src/Generated/Models/StaticFileChunkingStrategy.cs index a86690ab1..f59a5ede5 100644 --- a/src/Generated/Models/StaticFileChunkingStrategy.cs +++ b/src/Generated/Models/StaticFileChunkingStrategy.cs @@ -9,13 +9,9 @@ namespace OpenAI.VectorStores { public partial class StaticFileChunkingStrategy : FileChunkingStrategy { - internal StaticFileChunkingStrategy(string type, IDictionary serializedAdditionalRawData, InternalStaticChunkingStrategyDetails internalDetails) : base(type, serializedAdditionalRawData) + internal StaticFileChunkingStrategy(string @type, IDictionary additionalBinaryDataProperties, InternalStaticChunkingStrategyDetails internalDetails) : base(@type, additionalBinaryDataProperties) { _internalDetails = internalDetails; } - - internal StaticFileChunkingStrategy() - { - } } } diff --git a/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs b/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs index 016815b5a..ccb709a79 100644 --- a/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs +++ b/src/Generated/Models/StreamingChatCompletionUpdate.Serialization.cs @@ -7,46 +7,51 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class StreamingChatCompletionUpdate : IJsonModel { + internal StreamingChatCompletionUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(StreamingChatCompletionUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(CompletionId); + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("choices") != true) + if (Optional.IsDefined(SystemFingerprint) && _additionalBinaryDataProperties?.ContainsKey("system_fingerprint") != true) { - writer.WritePropertyName("choices"u8); - writer.WriteStartArray(); - foreach (var item in Choices) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); } - if (SerializedAdditionalRawData?.ContainsKey("created") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - writer.WritePropertyName("created"u8); - writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(CompletionId); } - if (SerializedAdditionalRawData?.ContainsKey("service_tier") != true && Optional.IsDefined(ServiceTier)) + if (Optional.IsDefined(ServiceTier) && _additionalBinaryDataProperties?.ContainsKey("service_tier") != true) { if (ServiceTier != null) { @@ -55,27 +60,32 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode } else { - writer.WriteNull("service_tier"); + writer.WriteNull("serviceTier"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("system_fingerprint") != true && Optional.IsDefined(SystemFingerprint)) + if (_additionalBinaryDataProperties?.ContainsKey("choices") != true) { - writer.WritePropertyName("system_fingerprint"u8); - writer.WriteStringValue(SystemFingerprint); + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (InternalCreateChatCompletionStreamResponseChoice item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created") != true) { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true && Optional.IsDefined(Usage)) + if (Optional.IsDefined(Usage) && _additionalBinaryDataProperties?.ContainsKey("usage") != true) { writer.WritePropertyName("usage"u8); writer.WriteObjectValue(Usage, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -83,7 +93,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -92,118 +102,114 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode #endif } } - writer.WriteEndObject(); } - StreamingChatCompletionUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + StreamingChatCompletionUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual StreamingChatCompletionUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(StreamingChatCompletionUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeStreamingChatCompletionUpdate(document.RootElement, options); } - internal static StreamingChatCompletionUpdate DeserializeStreamingChatCompletionUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static StreamingChatCompletionUpdate DeserializeStreamingChatCompletionUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; - IReadOnlyList choices = default; - DateTimeOffset created = default; string model = default; - InternalCreateChatCompletionStreamResponseServiceTier? serviceTier = default; string systemFingerprint = default; InternalCreateChatCompletionStreamResponseObject @object = default; + string completionId = default; + InternalCreateChatCompletionStreamResponseServiceTier? serviceTier = default; + IReadOnlyList choices = default; + DateTimeOffset createdAt = default; ChatTokenUsage usage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("model"u8)) { - id = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("choices"u8)) + if (prop.NameEquals("system_fingerprint"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(InternalCreateChatCompletionStreamResponseChoice.DeserializeInternalCreateChatCompletionStreamResponseChoice(item, options)); - } - choices = array; + systemFingerprint = prop.Value.GetString(); continue; } - if (property.NameEquals("created"u8)) + if (prop.NameEquals("object"u8)) { - created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + @object = new InternalCreateChatCompletionStreamResponseObject(prop.Value.GetString()); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("id"u8)) { - model = property.Value.GetString(); + completionId = prop.Value.GetString(); continue; } - if (property.NameEquals("service_tier"u8)) + if (prop.NameEquals("service_tier"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { serviceTier = null; continue; } - serviceTier = new InternalCreateChatCompletionStreamResponseServiceTier(property.Value.GetString()); + serviceTier = new InternalCreateChatCompletionStreamResponseServiceTier(prop.Value.GetString()); continue; } - if (property.NameEquals("system_fingerprint"u8)) + if (prop.NameEquals("choices"u8)) { - systemFingerprint = property.Value.GetString(); + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) + { + array.Add(InternalCreateChatCompletionStreamResponseChoice.DeserializeInternalCreateChatCompletionStreamResponseChoice(item, options)); + } + choices = array; continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("created"u8)) { - @object = new InternalCreateChatCompletionStreamResponseObject(property.Value.GetString()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - usage = ChatTokenUsage.DeserializeChatTokenUsage(property.Value, options); + usage = ChatTokenUsage.DeserializeChatTokenUsage(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new StreamingChatCompletionUpdate( - id, - choices, - created, model, - serviceTier, systemFingerprint, @object, + completionId, + serviceTier, + choices, + createdAt, usage, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -213,15 +219,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - StreamingChatCompletionUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + StreamingChatCompletionUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual StreamingChatCompletionUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeStreamingChatCompletionUpdate(document.RootElement, options); } default: @@ -231,15 +238,20 @@ StreamingChatCompletionUpdate IPersistableModel.C string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static StreamingChatCompletionUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(StreamingChatCompletionUpdate streamingChatCompletionUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeStreamingChatCompletionUpdate(document.RootElement); + if (streamingChatCompletionUpdate == null) + { + return null; + } + return BinaryContent.Create(streamingChatCompletionUpdate, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator StreamingChatCompletionUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeStreamingChatCompletionUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/StreamingChatCompletionUpdate.cs b/src/Generated/Models/StreamingChatCompletionUpdate.cs index 471658517..1271eb74d 100644 --- a/src/Generated/Models/StreamingChatCompletionUpdate.cs +++ b/src/Generated/Models/StreamingChatCompletionUpdate.cs @@ -10,36 +10,37 @@ namespace OpenAI.Chat { public partial class StreamingChatCompletionUpdate { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal StreamingChatCompletionUpdate(string completionId, IEnumerable choices, DateTimeOffset createdAt, string model) - { - Argument.AssertNotNull(completionId, nameof(completionId)); - Argument.AssertNotNull(choices, nameof(choices)); - Argument.AssertNotNull(model, nameof(model)); + private protected IDictionary _additionalBinaryDataProperties; + internal StreamingChatCompletionUpdate(string model, string completionId, IEnumerable choices, DateTimeOffset createdAt) + { + Model = model; CompletionId = completionId; Choices = choices.ToList(); CreatedAt = createdAt; - Model = model; } - internal StreamingChatCompletionUpdate(string completionId, IReadOnlyList choices, DateTimeOffset createdAt, string model, InternalCreateChatCompletionStreamResponseServiceTier? serviceTier, string systemFingerprint, InternalCreateChatCompletionStreamResponseObject @object, ChatTokenUsage usage, IDictionary serializedAdditionalRawData) + internal StreamingChatCompletionUpdate(string model, string systemFingerprint, InternalCreateChatCompletionStreamResponseObject @object, string completionId, InternalCreateChatCompletionStreamResponseServiceTier? serviceTier, IReadOnlyList choices, DateTimeOffset createdAt, ChatTokenUsage usage, IDictionary additionalBinaryDataProperties) { + Model = model; + SystemFingerprint = systemFingerprint; + this.Object = @object; CompletionId = completionId; + ServiceTier = serviceTier; Choices = choices; CreatedAt = createdAt; - Model = model; - ServiceTier = serviceTier; - SystemFingerprint = systemFingerprint; - Object = @object; Usage = usage; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal StreamingChatCompletionUpdate() - { - } public string Model { get; } + public string SystemFingerprint { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/StreamingChatFunctionCallUpdate.Serialization.cs b/src/Generated/Models/StreamingChatFunctionCallUpdate.Serialization.cs index 2a2ce5d6a..465dc3953 100644 --- a/src/Generated/Models/StreamingChatFunctionCallUpdate.Serialization.cs +++ b/src/Generated/Models/StreamingChatFunctionCallUpdate.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { @@ -14,26 +15,31 @@ public partial class StreamingChatFunctionCallUpdate : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(StreamingChatFunctionCallUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(FunctionName)) + if (Optional.IsDefined(FunctionName) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(FunctionName); } - if (SerializedAdditionalRawData?.ContainsKey("arguments") != true && Optional.IsDefined(FunctionArgumentsUpdate)) + if (Optional.IsDefined(FunctionArgumentsUpdate) && _additionalBinaryDataProperties?.ContainsKey("arguments") != true) { writer.WritePropertyName("arguments"u8); - SerializeFunctionArgumentsUpdateValue(writer, options); + this.SerializeFunctionArgumentsUpdateValue(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - StreamingChatFunctionCallUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + StreamingChatFunctionCallUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual StreamingChatFunctionCallUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(StreamingChatFunctionCallUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeStreamingChatFunctionCallUpdate(document.RootElement, options); } - internal static StreamingChatFunctionCallUpdate DeserializeStreamingChatFunctionCallUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static StreamingChatFunctionCallUpdate DeserializeStreamingChatFunctionCallUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string name = default; - BinaryData arguments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string functionName = default; + BinaryData functionArgumentsUpdate = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + functionName = prop.Value.GetString(); continue; } - if (property.NameEquals("arguments"u8)) + if (prop.NameEquals("arguments"u8)) { - DeserializeFunctionArgumentsUpdateValue(property, ref arguments); + DeserializeFunctionArgumentsUpdateValue(prop, ref functionArgumentsUpdate); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new StreamingChatFunctionCallUpdate(name, arguments, serializedAdditionalRawData); + return new StreamingChatFunctionCallUpdate(functionName, functionArgumentsUpdate, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - StreamingChatFunctionCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + StreamingChatFunctionCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual StreamingChatFunctionCallUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeStreamingChatFunctionCallUpdate(document.RootElement, options); } default: @@ -130,15 +133,20 @@ StreamingChatFunctionCallUpdate IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static StreamingChatFunctionCallUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(StreamingChatFunctionCallUpdate streamingChatFunctionCallUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeStreamingChatFunctionCallUpdate(document.RootElement); + if (streamingChatFunctionCallUpdate == null) + { + return null; + } + return BinaryContent.Create(streamingChatFunctionCallUpdate, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator StreamingChatFunctionCallUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeStreamingChatFunctionCallUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/StreamingChatFunctionCallUpdate.cs b/src/Generated/Models/StreamingChatFunctionCallUpdate.cs index 2872f9272..b8cb58764 100644 --- a/src/Generated/Models/StreamingChatFunctionCallUpdate.cs +++ b/src/Generated/Models/StreamingChatFunctionCallUpdate.cs @@ -9,16 +9,23 @@ namespace OpenAI.Chat { public partial class StreamingChatFunctionCallUpdate { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal StreamingChatFunctionCallUpdate() { } - internal StreamingChatFunctionCallUpdate(string functionName, BinaryData functionArgumentsUpdate, IDictionary serializedAdditionalRawData) + internal StreamingChatFunctionCallUpdate(string functionName, BinaryData functionArgumentsUpdate, IDictionary additionalBinaryDataProperties) { FunctionName = functionName; FunctionArgumentsUpdate = functionArgumentsUpdate; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/StreamingChatToolCallUpdate.Serialization.cs b/src/Generated/Models/StreamingChatToolCallUpdate.Serialization.cs index e88d5d247..57c15eb9f 100644 --- a/src/Generated/Models/StreamingChatToolCallUpdate.Serialization.cs +++ b/src/Generated/Models/StreamingChatToolCallUpdate.Serialization.cs @@ -7,43 +7,53 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class StreamingChatToolCallUpdate : IJsonModel { + internal StreamingChatToolCallUpdate() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(StreamingChatToolCallUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("index") != true) + if (_additionalBinaryDataProperties?.ContainsKey("index") != true) { writer.WritePropertyName("index"u8); writer.WriteNumberValue(Index); } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(ToolCallId)) + if (Optional.IsDefined(Function) && _additionalBinaryDataProperties?.ContainsKey("function") != true) { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(ToolCallId); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) { writer.WritePropertyName("type"u8); writer.WriteStringValue(Kind.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("function") != true && Optional.IsDefined(Function)) + if (Optional.IsDefined(ToolCallId) && _additionalBinaryDataProperties?.ContainsKey("id") != true) { - writer.WritePropertyName("function"u8); - writer.WriteObjectValue(Function, options); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(ToolCallId); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -51,7 +61,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -60,79 +70,75 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - StreamingChatToolCallUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + StreamingChatToolCallUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual StreamingChatToolCallUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(StreamingChatToolCallUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeStreamingChatToolCallUpdate(document.RootElement, options); } - internal static StreamingChatToolCallUpdate DeserializeStreamingChatToolCallUpdate(JsonElement element, ModelReaderWriterOptions options = null) + internal static StreamingChatToolCallUpdate DeserializeStreamingChatToolCallUpdate(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } int index = default; - string id = default; - ChatToolCallKind type = default; InternalChatCompletionMessageToolCallChunkFunction function = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Chat.ChatToolCallKind kind = default; + string toolCallId = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("index"u8)) + if (prop.NameEquals("index"u8)) { - index = property.Value.GetInt32(); + index = prop.Value.GetInt32(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("function"u8)) { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - type = property.Value.GetString().ToChatToolCallKind(); + function = InternalChatCompletionMessageToolCallChunkFunction.DeserializeInternalChatCompletionMessageToolCallChunkFunction(prop.Value, options); continue; } - if (property.NameEquals("function"u8)) + if (prop.NameEquals("type"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - function = InternalChatCompletionMessageToolCallChunkFunction.DeserializeInternalChatCompletionMessageToolCallChunkFunction(property.Value, options); + kind = prop.Value.GetString().ToChatToolCallKind(); + continue; + } + if (prop.NameEquals("id"u8)) + { + toolCallId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new StreamingChatToolCallUpdate(index, id, type, function, serializedAdditionalRawData); + return new StreamingChatToolCallUpdate(index, function, kind, toolCallId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -142,15 +148,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - StreamingChatToolCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + StreamingChatToolCallUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual StreamingChatToolCallUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeStreamingChatToolCallUpdate(document.RootElement, options); } default: @@ -160,15 +167,20 @@ StreamingChatToolCallUpdate IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static StreamingChatToolCallUpdate FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(StreamingChatToolCallUpdate streamingChatToolCallUpdate) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeStreamingChatToolCallUpdate(document.RootElement); + if (streamingChatToolCallUpdate == null) + { + return null; + } + return BinaryContent.Create(streamingChatToolCallUpdate, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator StreamingChatToolCallUpdate(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeStreamingChatToolCallUpdate(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/StreamingChatToolCallUpdate.cs b/src/Generated/Models/StreamingChatToolCallUpdate.cs index b50ad6c72..299399632 100644 --- a/src/Generated/Models/StreamingChatToolCallUpdate.cs +++ b/src/Generated/Models/StreamingChatToolCallUpdate.cs @@ -9,21 +9,23 @@ namespace OpenAI.Chat { public partial class StreamingChatToolCallUpdate { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal StreamingChatToolCallUpdate(int index, string toolCallId, ChatToolCallKind kind, InternalChatCompletionMessageToolCallChunkFunction function, IDictionary serializedAdditionalRawData) + internal StreamingChatToolCallUpdate(int index, InternalChatCompletionMessageToolCallChunkFunction function, Chat.ChatToolCallKind kind, string toolCallId, IDictionary additionalBinaryDataProperties) { Index = index; - ToolCallId = toolCallId; - Kind = kind; Function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; + Kind = kind; + ToolCallId = toolCallId; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal StreamingChatToolCallUpdate() + public int Index { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - - public int Index { get; } } } diff --git a/src/Generated/Models/SystemChatMessage.Serialization.cs b/src/Generated/Models/SystemChatMessage.Serialization.cs index a5ca37aaa..620f4d85d 100644 --- a/src/Generated/Models/SystemChatMessage.Serialization.cs +++ b/src/Generated/Models/SystemChatMessage.Serialization.cs @@ -7,68 +7,81 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class SystemChatMessage : IJsonModel { - SystemChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(SystemChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(SystemChatMessage)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(ParticipantName) && _additionalBinaryDataProperties?.ContainsKey("name") != true) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(ParticipantName); } + } + + SystemChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (SystemChatMessage)JsonModelCreateCore(ref reader, options); + 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(SystemChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeSystemChatMessage(document.RootElement, options); } - internal static SystemChatMessage DeserializeSystemChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static SystemChatMessage DeserializeSystemChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string name = default; - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string participantName = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("role"u8)) { - name = property.Value.GetString(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("content"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + DeserializeContentValue(prop, ref content); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("name"u8)) { - DeserializeContentValue(property, ref content); + participantName = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. - return new SystemChatMessage(role, content ?? new ChatMessageContent(), serializedAdditionalRawData, name); + return new SystemChatMessage(role, content ?? new ChatMessageContent(), additionalBinaryDataProperties, participantName); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -78,15 +91,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions o } } - SystemChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + SystemChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (SystemChatMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeSystemChatMessage(document.RootElement, options); } default: @@ -96,15 +110,20 @@ SystemChatMessage IPersistableModel.Create(BinaryData data, M string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new SystemChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(SystemChatMessage systemChatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeSystemChatMessage(document.RootElement); + if (systemChatMessage == null) + { + return null; + } + return BinaryContent.Create(systemChatMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator SystemChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeSystemChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/SystemChatMessage.cs b/src/Generated/Models/SystemChatMessage.cs index dfd6b9afd..0785ec94e 100644 --- a/src/Generated/Models/SystemChatMessage.cs +++ b/src/Generated/Models/SystemChatMessage.cs @@ -9,13 +9,9 @@ namespace OpenAI.Chat { public partial class SystemChatMessage : ChatMessage { - internal SystemChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) + internal SystemChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string participantName) : base(role, content, additionalBinaryDataProperties) { ParticipantName = participantName; } - - internal SystemChatMessage() - { - } } } diff --git a/src/Generated/Models/ThreadCreationOptions.Serialization.cs b/src/Generated/Models/ThreadCreationOptions.Serialization.cs index a415df841..8fd981fe1 100644 --- a/src/Generated/Models/ThreadCreationOptions.Serialization.cs +++ b/src/Generated/Models/ThreadCreationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,56 +15,66 @@ public partial class ThreadCreationOptions : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ThreadCreationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("messages") != true && Optional.IsCollectionDefined(InternalMessages)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { - writer.WritePropertyName("messages"u8); - writer.WriteStartArray(); - foreach (var item in InternalMessages) + if (Metadata != null) { - writer.WriteObjectValue(item, options); + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"u8); } - writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) { if (ToolResources != null) { writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); + writer.WriteObjectValue(ToolResources, options); } else { - writer.WriteNull("tool_resources"); + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(InternalMessages) && _additionalBinaryDataProperties?.ContainsKey("messages") != true) { - if (Metadata != null) - { - writer.WritePropertyName("metadata"u8); - writer.WriteStartObject(); - foreach (var item in Metadata) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - else + writer.WritePropertyName("messages"u8); + writer.WriteStartArray(); + foreach (MessageCreationOptions item in InternalMessages) { - writer.WriteNull("metadata"); + writer.WriteObjectValue(item, options); } + writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -71,7 +82,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -80,88 +91,91 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - ThreadCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ThreadCreationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ThreadCreationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeThreadCreationOptions(document.RootElement, options); } - internal static ThreadCreationOptions DeserializeThreadCreationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadCreationOptions DeserializeThreadCreationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - IList messages = default; - ToolResources toolResources = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ToolResources toolResources = default; + IList internalMessages = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("messages"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) { - array.Add(MessageCreationOptions.DeserializeMessageCreationOptions(item, options)); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } - messages = array; + metadata = dictionary; continue; } - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { toolResources = null; continue; } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("messages"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + array.Add(MessageCreationOptions.DeserializeMessageCreationOptions(item, options)); } - metadata = dictionary; + internalMessages = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ThreadCreationOptions(messages ?? new ChangeTrackingList(), toolResources, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new ThreadCreationOptions(metadata ?? new ChangeTrackingDictionary(), toolResources, internalMessages ?? new ChangeTrackingList(), additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -171,15 +185,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - ThreadCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ThreadCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ThreadCreationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeThreadCreationOptions(document.RootElement, options); } default: @@ -189,15 +204,20 @@ ThreadCreationOptions IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ThreadCreationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ThreadCreationOptions threadCreationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadCreationOptions(document.RootElement); + if (threadCreationOptions == null) + { + return null; + } + return BinaryContent.Create(threadCreationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ThreadCreationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeThreadCreationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ThreadCreationOptions.cs b/src/Generated/Models/ThreadCreationOptions.cs index 450cf612a..7675b5648 100644 --- a/src/Generated/Models/ThreadCreationOptions.cs +++ b/src/Generated/Models/ThreadCreationOptions.cs @@ -4,25 +4,34 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadCreationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ThreadCreationOptions() { - InternalMessages = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); + InternalMessages = new ChangeTrackingList(); } - internal ThreadCreationOptions(IList internalMessages, ToolResources toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadCreationOptions(IDictionary metadata, ToolResources toolResources, IList internalMessages, IDictionary additionalBinaryDataProperties) { - InternalMessages = internalMessages; - ToolResources = toolResources; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + ToolResources = toolResources; + InternalMessages = internalMessages; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ThreadDeletionResult.Serialization.cs b/src/Generated/Models/ThreadDeletionResult.Serialization.cs index ed9dba9f8..273d1f6e6 100644 --- a/src/Generated/Models/ThreadDeletionResult.Serialization.cs +++ b/src/Generated/Models/ThreadDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadDeletionResult : IJsonModel { + internal ThreadDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ThreadDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(ThreadId); - } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Deleted); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(ThreadId); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr #endif } } - writer.WriteEndObject(); } - ThreadDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ThreadDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ThreadDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeThreadDeletionResult(document.RootElement, options); } - internal static ThreadDeletionResult DeserializeThreadDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadDeletionResult DeserializeThreadDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; bool deleted = default; + string threadId = default; InternalDeleteThreadResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("id"u8)) { - deleted = property.Value.GetBoolean(); + threadId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteThreadResponseObject(property.Value.GetString()); + @object = new InternalDeleteThreadResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ThreadDeletionResult(id, deleted, @object, serializedAdditionalRawData); + return new ThreadDeletionResult(deleted, threadId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOption } } - ThreadDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ThreadDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ThreadDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeThreadDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ ThreadDeletionResult IPersistableModel.Create(BinaryData d string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ThreadDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ThreadDeletionResult threadDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadDeletionResult(document.RootElement); + if (threadDeletionResult == null) + { + return null; + } + return BinaryContent.Create(threadDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ThreadDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeThreadDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ThreadDeletionResult.cs b/src/Generated/Models/ThreadDeletionResult.cs index d0b06a680..209c7f80a 100644 --- a/src/Generated/Models/ThreadDeletionResult.cs +++ b/src/Generated/Models/ThreadDeletionResult.cs @@ -9,26 +9,28 @@ namespace OpenAI.Assistants { public partial class ThreadDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ThreadDeletionResult(string threadId, bool deleted) - { - Argument.AssertNotNull(threadId, nameof(threadId)); + private protected IDictionary _additionalBinaryDataProperties; - ThreadId = threadId; + internal ThreadDeletionResult(bool deleted, string threadId) + { Deleted = deleted; + ThreadId = threadId; } - internal ThreadDeletionResult(string threadId, bool deleted, InternalDeleteThreadResponseObject @object, IDictionary serializedAdditionalRawData) + internal ThreadDeletionResult(bool deleted, string threadId, InternalDeleteThreadResponseObject @object, IDictionary additionalBinaryDataProperties) { - ThreadId = threadId; Deleted = deleted; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + ThreadId = threadId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ThreadDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public bool Deleted { get; } } } diff --git a/src/Generated/Models/ThreadMessage.Serialization.cs b/src/Generated/Models/ThreadMessage.Serialization.cs index 333213907..6e31ee878 100644 --- a/src/Generated/Models/ThreadMessage.Serialization.cs +++ b/src/Generated/Models/ThreadMessage.Serialization.cs @@ -7,46 +7,51 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadMessage : IJsonModel { + internal ThreadMessage() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ThreadMessage)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("thread_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("thread_id") != true) { writer.WritePropertyName("thread_id"u8); writer.WriteStringValue(ThreadId); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("incomplete_details") != true) + if (_additionalBinaryDataProperties?.ContainsKey("incomplete_details") != true) { if (IncompleteDetails != null) { @@ -55,10 +60,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("incomplete_details"); + writer.WriteNull("incompleteDetails"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("completed_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed_at") != true) { if (CompletedAt != null) { @@ -67,10 +72,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("completed_at"); + writer.WriteNull("completedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("incomplete_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("incomplete_at") != true) { if (IncompleteAt != null) { @@ -79,25 +84,20 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("incomplete_at"); + writer.WriteNull("incompleteAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("role") != true) - { - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("content") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("content") != true) { writer.WritePropertyName("content"u8); writer.WriteStartArray(); - foreach (var item in Content) + foreach (MessageContent item in Content) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("assistant_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true) { if (AssistantId != null) { @@ -106,10 +106,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("assistant_id"); + writer.WriteNull("assistantId"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("run_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("run_id") != true) { if (RunId != null) { @@ -118,47 +118,62 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } else { - writer.WriteNull("run_id"); + writer.WriteNull("runId"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("attachments") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { - if (Attachments != null && Optional.IsCollectionDefined(Attachments)) + if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { - writer.WritePropertyName("attachments"u8); - writer.WriteStartArray(); - foreach (var item in Attachments) + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) { - writer.WriteObjectValue(item, options); + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item.Value); } - writer.WriteEndArray(); + writer.WriteEndObject(); } else { - writer.WriteNull("attachments"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - if (Metadata != null && Optional.IsCollectionDefined(Metadata)) + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("role") != true) + { + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToSerialString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("attachments") != true) + { + if (Attachments != null && Optional.IsCollectionDefined(Attachments)) { - writer.WritePropertyName("metadata"u8); - writer.WriteStartObject(); - foreach (var item in Metadata) + writer.WritePropertyName("attachments"u8); + writer.WriteStartArray(); + foreach (MessageCreationAttachment item in Attachments) { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); + writer.WriteObjectValue(item, options); } - writer.WriteEndObject(); + writer.WriteEndArray(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("attachments"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -166,7 +181,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -175,196 +190,199 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt #endif } } - writer.WriteEndObject(); } - ThreadMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ThreadMessage JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ThreadMessage)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeThreadMessage(document.RootElement, options); } - internal static ThreadMessage DeserializeThreadMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadMessage DeserializeThreadMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalMessageObjectObject @object = default; DateTimeOffset createdAt = default; string threadId = default; MessageStatus status = default; MessageFailureDetails incompleteDetails = default; DateTimeOffset? completedAt = default; DateTimeOffset? incompleteAt = default; - MessageRole role = default; IReadOnlyList content = default; string assistantId = default; string runId = default; - IReadOnlyList attachments = default; IReadOnlyDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalMessageObjectObject @object = default; + Assistants.MessageRole role = default; + IReadOnlyList attachments = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("id"u8)) { - @object = new InternalMessageObjectObject(property.Value.GetString()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("thread_id"u8)) + if (prop.NameEquals("thread_id"u8)) { - threadId = property.Value.GetString(); + threadId = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new MessageStatus(property.Value.GetString()); + status = new MessageStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("incomplete_details"u8)) + if (prop.NameEquals("incomplete_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { incompleteDetails = null; continue; } - incompleteDetails = MessageFailureDetails.DeserializeMessageFailureDetails(property.Value, options); + incompleteDetails = MessageFailureDetails.DeserializeMessageFailureDetails(prop.Value, options); continue; } - if (property.NameEquals("completed_at"u8)) + if (prop.NameEquals("completed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { completedAt = null; continue; } - completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("incomplete_at"u8)) + if (prop.NameEquals("incomplete_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { incompleteAt = null; continue; } - incompleteAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + incompleteAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("role"u8)) - { - role = property.Value.GetString().ToMessageRole(); - continue; - } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("content"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(MessageContent.DeserializeMessageContent(item, options)); } content = array; continue; } - if (property.NameEquals("assistant_id"u8)) + if (prop.NameEquals("assistant_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { assistantId = null; continue; } - assistantId = property.Value.GetString(); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("run_id"u8)) + if (prop.NameEquals("run_id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { runId = null; continue; } - runId = property.Value.GetString(); + runId = prop.Value.GetString(); continue; } - if (property.NameEquals("attachments"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - attachments = new ChangeTrackingList(); + metadata = new ChangeTrackingDictionary(); continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) { - array.Add(MessageCreationAttachment.DeserializeMessageCreationAttachment(item, options)); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } - attachments = array; + metadata = dictionary; + continue; + } + if (prop.NameEquals("object"u8)) + { + @object = new InternalMessageObjectObject(prop.Value.GetString()); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("role"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + role = prop.Value.GetString().ToMessageRole(); + continue; + } + if (prop.NameEquals("attachments"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - metadata = new ChangeTrackingDictionary(); + attachments = new ChangeTrackingList(); continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + List array = new List(); + foreach (var item in prop.Value.EnumerateArray()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + array.Add(MessageCreationAttachment.DeserializeMessageCreationAttachment(item, options)); } - metadata = dictionary; + attachments = array; continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ThreadMessage( id, - @object, createdAt, threadId, status, incompleteDetails, completedAt, incompleteAt, - role, content, assistantId, runId, - attachments, metadata, - serializedAdditionalRawData); + @object, + role, + attachments, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -374,15 +392,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions optio } } - ThreadMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ThreadMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ThreadMessage 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeThreadMessage(document.RootElement, options); } default: @@ -392,15 +411,20 @@ ThreadMessage IPersistableModel.Create(BinaryData data, ModelRead string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ThreadMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ThreadMessage threadMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadMessage(document.RootElement); + if (threadMessage == null) + { + return null; + } + return BinaryContent.Create(threadMessage, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ThreadMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeThreadMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ThreadMessage.cs b/src/Generated/Models/ThreadMessage.cs index ba5967d55..b18cc0085 100644 --- a/src/Generated/Models/ThreadMessage.cs +++ b/src/Generated/Models/ThreadMessage.cs @@ -5,18 +5,16 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadMessage { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageFailureDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IEnumerable content, string assistantId, string runId, IEnumerable attachments, IReadOnlyDictionary metadata) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + private protected IDictionary _additionalBinaryDataProperties; + internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageFailureDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, string assistantId, string runId, Assistants.MessageRole role, IEnumerable attachments) + { Id = id; CreatedAt = createdAt; ThreadId = threadId; @@ -24,48 +22,59 @@ internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, Mes IncompleteDetails = incompleteDetails; CompletedAt = completedAt; IncompleteAt = incompleteAt; - Role = role; - Content = content.ToList(); + Content = new ChangeTrackingList(); AssistantId = assistantId; RunId = runId; - Attachments = attachments?.ToList(); - Metadata = metadata; + Metadata = new ChangeTrackingDictionary(); + Role = role; + Attachments = attachments.ToList(); } - internal ThreadMessage(string id, InternalMessageObjectObject @object, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageFailureDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IReadOnlyList content, string assistantId, string runId, IReadOnlyList attachments, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageFailureDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, IReadOnlyList content, string assistantId, string runId, IReadOnlyDictionary metadata, InternalMessageObjectObject @object, Assistants.MessageRole role, IReadOnlyList attachments, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; CreatedAt = createdAt; ThreadId = threadId; Status = status; IncompleteDetails = incompleteDetails; CompletedAt = completedAt; IncompleteAt = incompleteAt; - Role = role; Content = content; AssistantId = assistantId; RunId = runId; - Attachments = attachments; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ThreadMessage() - { + this.Object = @object; + Role = role; + Attachments = attachments; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public string ThreadId { get; } + public MessageStatus Status { get; } + public MessageFailureDetails IncompleteDetails { get; } + public DateTimeOffset? CompletedAt { get; } + public DateTimeOffset? IncompleteAt { get; } + public IReadOnlyList Content { get; } + public string AssistantId { get; } + public string RunId { get; } + public IReadOnlyDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ThreadModificationOptions.Serialization.cs b/src/Generated/Models/ThreadModificationOptions.Serialization.cs index e53955c26..b1bad14a1 100644 --- a/src/Generated/Models/ThreadModificationOptions.Serialization.cs +++ b/src/Generated/Models/ThreadModificationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,19 @@ public partial class ThreadModificationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ThreadModificationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_resources") != true && Optional.IsDefined(ToolResources)) - { - if (ToolResources != null) - { - writer.WritePropertyName("tool_resources"u8); - writer.WriteObjectValue(ToolResources, options); - } - else - { - writer.WriteNull("tool_resources"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -42,18 +36,35 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); + } + } + if (Optional.IsDefined(ToolResources) && _additionalBinaryDataProperties?.ContainsKey("tool_resources") != true) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("toolResources"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +72,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,73 +81,76 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - ThreadModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ThreadModificationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ThreadModificationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeThreadModificationOptions(document.RootElement, options); } - internal static ThreadModificationOptions DeserializeThreadModificationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadModificationOptions DeserializeThreadModificationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ToolResources toolResources = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ToolResources toolResources = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_resources"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolResources = null; continue; } - toolResources = Assistants.ToolResources.DeserializeToolResources(property.Value, options); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("tool_resources"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + toolResources = null; continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + toolResources = ToolResources.DeserializeToolResources(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ThreadModificationOptions(toolResources, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new ThreadModificationOptions(metadata ?? new ChangeTrackingDictionary(), toolResources, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -146,15 +160,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - ThreadModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ThreadModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ThreadModificationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeThreadModificationOptions(document.RootElement, options); } default: @@ -164,15 +179,20 @@ ThreadModificationOptions IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ThreadModificationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ThreadModificationOptions threadModificationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadModificationOptions(document.RootElement); + if (threadModificationOptions == null) + { + return null; + } + return BinaryContent.Create(threadModificationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ThreadModificationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeThreadModificationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ThreadModificationOptions.cs b/src/Generated/Models/ThreadModificationOptions.cs index b26090b10..261bcaf15 100644 --- a/src/Generated/Models/ThreadModificationOptions.cs +++ b/src/Generated/Models/ThreadModificationOptions.cs @@ -4,23 +4,32 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadModificationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ThreadModificationOptions() { Metadata = new ChangeTrackingDictionary(); } - internal ThreadModificationOptions(ToolResources toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadModificationOptions(IDictionary metadata, ToolResources toolResources, IDictionary additionalBinaryDataProperties) { - ToolResources = toolResources; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + ToolResources = toolResources; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } + public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ThreadRun.Serialization.cs b/src/Generated/Models/ThreadRun.Serialization.cs index d5cb1a2ce..cce0cb264 100644 --- a/src/Generated/Models/ThreadRun.Serialization.cs +++ b/src/Generated/Models/ThreadRun.Serialization.cs @@ -7,63 +7,56 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadRun : IJsonModel { + internal ThreadRun() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ThreadRun)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("thread_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("thread_id") != true) { writer.WritePropertyName("thread_id"u8); writer.WriteStringValue(ThreadId); } - if (SerializedAdditionalRawData?.ContainsKey("assistant_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("required_action") != true) - { - if (_internalRequiredAction != null) - { - writer.WritePropertyName("required_action"u8); - writer.WriteObjectValue(_internalRequiredAction, options); - } - else - { - writer.WriteNull("required_action"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("last_error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_error") != true) { if (LastError != null) { @@ -72,10 +65,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("last_error"); + writer.WriteNull("lastError"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("expires_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("expires_at") != true) { if (ExpiresAt != null) { @@ -84,10 +77,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("expires_at"); + writer.WriteNull("expiresAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("started_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("started_at") != true) { if (StartedAt != null) { @@ -96,10 +89,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("started_at"); + writer.WriteNull("startedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("cancelled_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cancelled_at") != true) { if (CancelledAt != null) { @@ -108,10 +101,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("cancelled_at"); + writer.WriteNull("cancelledAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("failed_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("failed_at") != true) { if (FailedAt != null) { @@ -120,10 +113,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("failed_at"); + writer.WriteNull("failedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("completed_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed_at") != true) { if (CompletedAt != null) { @@ -132,10 +125,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("completed_at"); + writer.WriteNull("completedAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("incomplete_details") != true) + if (_additionalBinaryDataProperties?.ContainsKey("incomplete_details") != true) { if (IncompleteDetails != null) { @@ -144,30 +137,30 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("incomplete_details"); + writer.WriteNull("incompleteDetails"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("model") != true) + if (_additionalBinaryDataProperties?.ContainsKey("model") != true) { writer.WritePropertyName("model"u8); writer.WriteStringValue(Model); } - if (SerializedAdditionalRawData?.ContainsKey("instructions") != true) + if (_additionalBinaryDataProperties?.ContainsKey("instructions") != true) { writer.WritePropertyName("instructions"u8); writer.WriteStringValue(Instructions); } - if (SerializedAdditionalRawData?.ContainsKey("tools") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("tools") != true) { writer.WritePropertyName("tools"u8); writer.WriteStartArray(); - foreach (var item in Tools) + foreach (ToolDefinition item in Tools) { writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { @@ -176,16 +169,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("usage") != true) + if (_additionalBinaryDataProperties?.ContainsKey("usage") != true) { if (Usage != null) { @@ -194,10 +192,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("usage"); + writer.WriteNull("usage"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true && Optional.IsDefined(Temperature)) + if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true) { if (Temperature != null) { @@ -206,89 +204,106 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } else { - writer.WriteNull("temperature"); + writer.WriteNull("temperature"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("top_p") != true && Optional.IsDefined(NucleusSamplingFactor)) + if (_additionalBinaryDataProperties?.ContainsKey("truncation_strategy") != true) { - if (NucleusSamplingFactor != null) + if (TruncationStrategy != null) { - writer.WritePropertyName("top_p"u8); - writer.WriteNumberValue(NucleusSamplingFactor.Value); + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); } else { - writer.WriteNull("top_p"); + writer.WriteNull("truncationStrategy"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_prompt_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - if (MaxInputTokenCount != null) + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("response_format") != true) + { + if (ResponseFormat != null) { - writer.WritePropertyName("max_prompt_tokens"u8); - writer.WriteNumberValue(MaxInputTokenCount.Value); + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); } else { - writer.WriteNull("max_prompt_tokens"); + writer.WriteNull("responseFormat"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("max_completion_tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("tool_choice") != true) { - if (MaxOutputTokenCount != null) + if (ToolConstraint != null) { - writer.WritePropertyName("max_completion_tokens"u8); - writer.WriteNumberValue(MaxOutputTokenCount.Value); + writer.WritePropertyName("tool_choice"u8); + writer.WriteObjectValue(ToolConstraint, options); } else { - writer.WriteNull("max_completion_tokens"); + writer.WriteNull("toolChoice"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("truncation_strategy") != true) + if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true) { - if (TruncationStrategy != null) + if (NucleusSamplingFactor != null) { - writer.WritePropertyName("truncation_strategy"u8); - writer.WriteObjectValue(TruncationStrategy, options); + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); } else { - writer.WriteNull("truncation_strategy"); + writer.WriteNull("topP"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("tool_choice") != true) + if (_additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true) { - if (ToolConstraint != null) + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); + } + if (_additionalBinaryDataProperties?.ContainsKey("max_prompt_tokens") != true) + { + if (MaxInputTokenCount != null) { - writer.WritePropertyName("tool_choice"u8); - writer.WriteObjectValue(ToolConstraint, options); + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxInputTokenCount.Value); } else { - writer.WriteNull("tool_choice"); + writer.WriteNull("maxPromptTokens"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true) + if (_additionalBinaryDataProperties?.ContainsKey("max_completion_tokens") != true) { - writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(AllowParallelToolCalls.Value); + if (MaxOutputTokenCount != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxOutputTokenCount.Value); + } + else + { + writer.WriteNull("maxCompletionTokens"u8); + } } - if (SerializedAdditionalRawData?.ContainsKey("response_format") != true) + if (_additionalBinaryDataProperties?.ContainsKey("required_action") != true) { - if (ResponseFormat != null) + if (_internalRequiredAction != null) { - writer.WritePropertyName("response_format"u8); - writer.WriteObjectValue(ResponseFormat, options); + writer.WritePropertyName("required_action"u8); + writer.WriteObjectValue(_internalRequiredAction, options); } else { - writer.WriteNull("response_format"); + writer.WriteNull("requiredAction"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -296,7 +311,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -305,36 +320,32 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions #endif } } - writer.WriteEndObject(); } - ThreadRun IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadRun IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ThreadRun JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ThreadRun)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeThreadRun(document.RootElement, options); } - internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalRunObjectObject @object = default; DateTimeOffset createdAt = default; string threadId = default; string assistantId = default; RunStatus status = default; - InternalRunRequiredAction requiredAction = default; RunError lastError = default; DateTimeOffset? expiresAt = default; DateTimeOffset? startedAt = default; @@ -348,262 +359,266 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW IReadOnlyDictionary metadata = default; RunTokenUsage usage = default; float? temperature = default; - float? topP = default; - int? maxPromptTokens = default; - int? maxCompletionTokens = default; RunTruncationStrategy truncationStrategy = default; - ToolConstraint toolChoice = default; - bool? parallelToolCalls = default; + InternalRunObjectObject @object = default; AssistantResponseFormat responseFormat = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) - { - @object = new InternalRunObjectObject(property.Value.GetString()); + ToolConstraint toolConstraint = default; + float? nucleusSamplingFactor = default; + bool? allowParallelToolCalls = default; + int? maxInputTokenCount = default; + int? maxOutputTokenCount = default; + InternalRunRequiredAction internalRequiredAction = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("created_at"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("thread_id"u8)) + if (prop.NameEquals("thread_id"u8)) { - threadId = property.Value.GetString(); + threadId = prop.Value.GetString(); continue; } - if (property.NameEquals("assistant_id"u8)) + if (prop.NameEquals("assistant_id"u8)) { - assistantId = property.Value.GetString(); + assistantId = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("status"u8)) { - status = new RunStatus(property.Value.GetString()); + status = new RunStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("required_action"u8)) + if (prop.NameEquals("last_error"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - requiredAction = null; - continue; - } - requiredAction = InternalRunRequiredAction.DeserializeInternalRunRequiredAction(property.Value, options); - continue; - } - if (property.NameEquals("last_error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { lastError = null; continue; } - lastError = RunError.DeserializeRunError(property.Value, options); + lastError = RunError.DeserializeRunError(prop.Value, options); continue; } - if (property.NameEquals("expires_at"u8)) + if (prop.NameEquals("expires_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { expiresAt = null; continue; } - expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("started_at"u8)) + if (prop.NameEquals("started_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { startedAt = null; continue; } - startedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + startedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("cancelled_at"u8)) + if (prop.NameEquals("cancelled_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { cancelledAt = null; continue; } - cancelledAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + cancelledAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("failed_at"u8)) + if (prop.NameEquals("failed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { failedAt = null; continue; } - failedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + failedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("completed_at"u8)) + if (prop.NameEquals("completed_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { completedAt = null; continue; } - completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("incomplete_details"u8)) + if (prop.NameEquals("incomplete_details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { incompleteDetails = null; continue; } - incompleteDetails = RunIncompleteDetails.DeserializeRunIncompleteDetails(property.Value, options); + incompleteDetails = RunIncompleteDetails.DeserializeRunIncompleteDetails(prop.Value, options); continue; } - if (property.NameEquals("model"u8)) + if (prop.NameEquals("model"u8)) { - model = property.Value.GetString(); + model = prop.Value.GetString(); continue; } - if (property.NameEquals("instructions"u8)) + if (prop.NameEquals("instructions"u8)) { - instructions = property.Value.GetString(); + instructions = prop.Value.GetString(); continue; } - if (property.NameEquals("tools"u8)) + if (prop.NameEquals("tools"u8)) { List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { array.Add(ToolDefinition.DeserializeToolDefinition(item, options)); } tools = array; continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { metadata = new ChangeTrackingDictionary(); continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } - if (property.NameEquals("usage"u8)) + if (prop.NameEquals("usage"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { usage = null; continue; } - usage = RunTokenUsage.DeserializeRunTokenUsage(property.Value, options); + usage = RunTokenUsage.DeserializeRunTokenUsage(prop.Value, options); continue; } - if (property.NameEquals("temperature"u8)) + if (prop.NameEquals("temperature"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { temperature = null; continue; } - temperature = property.Value.GetSingle(); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("top_p"u8)) + if (prop.NameEquals("truncation_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - topP = null; + truncationStrategy = null; continue; } - topP = property.Value.GetSingle(); + truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(prop.Value, options); continue; } - if (property.NameEquals("max_prompt_tokens"u8)) + if (prop.NameEquals("object"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + @object = new InternalRunObjectObject(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("response_format"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { - maxPromptTokens = null; + responseFormat = null; continue; } - maxPromptTokens = property.Value.GetInt32(); + responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options); continue; } - if (property.NameEquals("max_completion_tokens"u8)) + if (prop.NameEquals("tool_choice"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - maxCompletionTokens = null; + toolConstraint = null; continue; } - maxCompletionTokens = property.Value.GetInt32(); + toolConstraint = ToolConstraint.DeserializeToolConstraint(prop.Value, options); continue; } - if (property.NameEquals("truncation_strategy"u8)) + if (prop.NameEquals("top_p"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - truncationStrategy = null; + nucleusSamplingFactor = null; continue; } - truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(property.Value, options); + nucleusSamplingFactor = prop.Value.GetSingle(); + continue; + } + if (prop.NameEquals("parallel_tool_calls"u8)) + { + allowParallelToolCalls = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("tool_choice"u8)) + if (prop.NameEquals("max_prompt_tokens"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - toolChoice = null; + maxInputTokenCount = null; continue; } - toolChoice = Assistants.ToolConstraint.DeserializeToolConstraint(property.Value, options); + maxInputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("parallel_tool_calls"u8)) + if (prop.NameEquals("max_completion_tokens"u8)) { - parallelToolCalls = property.Value.GetBoolean(); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + maxOutputTokenCount = null; + continue; + } + maxOutputTokenCount = prop.Value.GetInt32(); continue; } - if (property.NameEquals("response_format"u8)) + if (prop.NameEquals("required_action"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - responseFormat = null; + internalRequiredAction = null; continue; } - responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(property.Value, options); + internalRequiredAction = InternalRunRequiredAction.DeserializeInternalRunRequiredAction(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new ThreadRun( id, - @object, createdAt, threadId, assistantId, status, - requiredAction, lastError, expiresAt, startedAt, @@ -617,20 +632,23 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW metadata, usage, temperature, - topP, - maxPromptTokens, - maxCompletionTokens, truncationStrategy, - toolChoice, - parallelToolCalls, + @object, responseFormat, - serializedAdditionalRawData); + toolConstraint, + nucleusSamplingFactor, + allowParallelToolCalls, + maxInputTokenCount, + maxOutputTokenCount, + internalRequiredAction, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -640,15 +658,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - ThreadRun IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ThreadRun IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ThreadRun 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeThreadRun(document.RootElement, options); } default: @@ -658,15 +677,20 @@ ThreadRun IPersistableModel.Create(BinaryData data, ModelReaderWriter string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ThreadRun FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ThreadRun threadRun) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadRun(document.RootElement); + if (threadRun == null) + { + return null; + } + return BinaryContent.Create(threadRun, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ThreadRun(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeThreadRun(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ThreadRun.cs b/src/Generated/Models/ThreadRun.cs index 65ab7b089..46d28f1e9 100644 --- a/src/Generated/Models/ThreadRun.cs +++ b/src/Generated/Models/ThreadRun.cs @@ -4,23 +4,49 @@ using System; using System.Collections.Generic; -using System.Linq; +using OpenAI; namespace OpenAI.Assistants { public partial class ThreadRun { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ThreadRun(string id, InternalRunObjectObject @object, DateTimeOffset createdAt, string threadId, string assistantId, RunStatus status, InternalRunRequiredAction internalRequiredAction, RunError lastError, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunIncompleteDetails incompleteDetails, string model, string instructions, IReadOnlyList tools, IReadOnlyDictionary metadata, RunTokenUsage usage, float? temperature, float? nucleusSamplingFactor, int? maxInputTokenCount, int? maxOutputTokenCount, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string assistantId, RunStatus status, RunError lastError, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunIncompleteDetails incompleteDetails, string model, string instructions, RunTokenUsage usage, RunTruncationStrategy truncationStrategy, AssistantResponseFormat responseFormat, ToolConstraint toolConstraint, bool? allowParallelToolCalls, int? maxInputTokenCount, int? maxOutputTokenCount, InternalRunRequiredAction internalRequiredAction) { Id = id; - Object = @object; CreatedAt = createdAt; ThreadId = threadId; AssistantId = assistantId; Status = status; + LastError = lastError; + ExpiresAt = expiresAt; + StartedAt = startedAt; + CancelledAt = cancelledAt; + FailedAt = failedAt; + CompletedAt = completedAt; + IncompleteDetails = incompleteDetails; + Model = model; + Instructions = instructions; + Tools = new ChangeTrackingList(); + Metadata = new ChangeTrackingDictionary(); + Usage = usage; + TruncationStrategy = truncationStrategy; + ResponseFormat = responseFormat; + ToolConstraint = toolConstraint; + AllowParallelToolCalls = allowParallelToolCalls; + MaxInputTokenCount = maxInputTokenCount; + MaxOutputTokenCount = maxOutputTokenCount; _internalRequiredAction = internalRequiredAction; + } + + internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string assistantId, RunStatus status, RunError lastError, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunIncompleteDetails incompleteDetails, string model, string instructions, IReadOnlyList tools, IReadOnlyDictionary metadata, RunTokenUsage usage, float? temperature, RunTruncationStrategy truncationStrategy, InternalRunObjectObject @object, AssistantResponseFormat responseFormat, ToolConstraint toolConstraint, float? nucleusSamplingFactor, bool? allowParallelToolCalls, int? maxInputTokenCount, int? maxOutputTokenCount, InternalRunRequiredAction internalRequiredAction, IDictionary additionalBinaryDataProperties) + { + Id = id; + CreatedAt = createdAt; + ThreadId = threadId; + AssistantId = assistantId; + Status = status; LastError = lastError; ExpiresAt = expiresAt; StartedAt = startedAt; @@ -34,39 +60,60 @@ internal ThreadRun(string id, InternalRunObjectObject @object, DateTimeOffset cr Metadata = metadata; Usage = usage; Temperature = temperature; - NucleusSamplingFactor = nucleusSamplingFactor; - MaxInputTokenCount = maxInputTokenCount; - MaxOutputTokenCount = maxOutputTokenCount; TruncationStrategy = truncationStrategy; + this.Object = @object; + ResponseFormat = responseFormat; ToolConstraint = toolConstraint; + NucleusSamplingFactor = nucleusSamplingFactor; AllowParallelToolCalls = allowParallelToolCalls; - ResponseFormat = responseFormat; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ThreadRun() - { + MaxInputTokenCount = maxInputTokenCount; + MaxOutputTokenCount = maxOutputTokenCount; + _internalRequiredAction = internalRequiredAction; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public string ThreadId { get; } + public string AssistantId { get; } + public RunStatus Status { get; } + public RunError LastError { get; } + public DateTimeOffset? ExpiresAt { get; } + public DateTimeOffset? StartedAt { get; } + public DateTimeOffset? CancelledAt { get; } + public DateTimeOffset? FailedAt { get; } + public DateTimeOffset? CompletedAt { get; } + public RunIncompleteDetails IncompleteDetails { get; } + public string Model { get; } + public string Instructions { get; } + public IReadOnlyList Tools { get; } + public IReadOnlyDictionary Metadata { get; } + public RunTokenUsage Usage { get; } + public float? Temperature { get; } + public RunTruncationStrategy TruncationStrategy { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ToolChatMessage.Serialization.cs b/src/Generated/Models/ToolChatMessage.Serialization.cs index ed9101ecb..c3072ce6b 100644 --- a/src/Generated/Models/ToolChatMessage.Serialization.cs +++ b/src/Generated/Models/ToolChatMessage.Serialization.cs @@ -7,68 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class ToolChatMessage : IJsonModel { - ToolChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal ToolChatMessage() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(ToolChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ToolChatMessage)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("tool_call_id") != true) + { + writer.WritePropertyName("tool_call_id"u8); + writer.WriteStringValue(ToolCallId); } + } + + ToolChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ToolChatMessage)JsonModelCreateCore(ref reader, options); + 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(ToolChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeToolChatMessage(document.RootElement, options); } - internal static ToolChatMessage DeserializeToolChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static ToolChatMessage DeserializeToolChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string toolCallId = default; - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string toolCallId = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_call_id"u8)) + if (prop.NameEquals("role"u8)) { - toolCallId = property.Value.GetString(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("content"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + DeserializeContentValue(prop, ref content); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("tool_call_id"u8)) { - DeserializeContentValue(property, ref content); + toolCallId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. - return new ToolChatMessage(role, content ?? new ChatMessageContent(), serializedAdditionalRawData, toolCallId); + return new ToolChatMessage(role, content ?? new ChatMessageContent(), additionalBinaryDataProperties, toolCallId); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -78,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - ToolChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ToolChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ToolChatMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeToolChatMessage(document.RootElement, options); } default: @@ -96,15 +114,20 @@ ToolChatMessage IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new ToolChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ToolChatMessage toolChatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeToolChatMessage(document.RootElement); + if (toolChatMessage == null) + { + return null; + } + return BinaryContent.Create(toolChatMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator ToolChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeToolChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ToolChatMessage.cs b/src/Generated/Models/ToolChatMessage.cs index dc9868382..6e671b9c4 100644 --- a/src/Generated/Models/ToolChatMessage.cs +++ b/src/Generated/Models/ToolChatMessage.cs @@ -9,15 +9,11 @@ namespace OpenAI.Chat { public partial class ToolChatMessage : ChatMessage { - internal ToolChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string toolCallId) : base(role, content, serializedAdditionalRawData) + internal ToolChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string toolCallId) : base(role, content, additionalBinaryDataProperties) { ToolCallId = toolCallId; } - internal ToolChatMessage() - { - } - public string ToolCallId { get; } } } diff --git a/src/Generated/Models/ToolConstraint.Serialization.cs b/src/Generated/Models/ToolConstraint.Serialization.cs index 2282c137b..c816ad7cc 100644 --- a/src/Generated/Models/ToolConstraint.Serialization.cs +++ b/src/Generated/Models/ToolConstraint.Serialization.cs @@ -6,22 +6,108 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { public partial class ToolConstraint : IJsonModel { + internal ToolConstraint() + { + } + + 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(ToolConstraint)} does not support writing '{format}' format."); + } + if (Optional.IsDefined(Function) && _additionalBinaryDataProperties?.ContainsKey("function") != true) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(_objectType); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + protected virtual ToolConstraint 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(ToolConstraint)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return ToolConstraint.DeserializeToolConstraint(document.RootElement, options); + } + + 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); + default: + throw new FormatException($"The model {nameof(ToolConstraint)} does not support writing '{options.Format}' format."); + } + } + + protected virtual ToolConstraint 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)) + { + return ToolConstraint.DeserializeToolConstraint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ToolConstraint)} does not support reading '{options.Format}' format."); + } + } + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ToolConstraint FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ToolConstraint toolConstraint) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeToolConstraint(document.RootElement); + if (toolConstraint == null) + { + return null; + } + return BinaryContent.Create(toolConstraint, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ToolConstraint(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return ToolConstraint.DeserializeToolConstraint(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ToolConstraint.cs b/src/Generated/Models/ToolConstraint.cs index 519953a5f..56d7f7543 100644 --- a/src/Generated/Models/ToolConstraint.cs +++ b/src/Generated/Models/ToolConstraint.cs @@ -9,15 +9,19 @@ namespace OpenAI.Assistants { public partial class ToolConstraint { - internal ToolConstraint(string objectType, InternalAssistantsNamedToolChoiceFunction function, IDictionary serializedAdditionalRawData) + private protected IDictionary _additionalBinaryDataProperties; + + internal ToolConstraint(InternalAssistantsNamedToolChoiceFunction function, string objectType, IDictionary additionalBinaryDataProperties) { - _objectType = objectType; Function = function; - SerializedAdditionalRawData = serializedAdditionalRawData; + _objectType = objectType; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal ToolConstraint() + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/ToolDefinition.Serialization.cs b/src/Generated/Models/ToolDefinition.Serialization.cs index 443582baf..123272c7e 100644 --- a/src/Generated/Models/ToolDefinition.Serialization.cs +++ b/src/Generated/Models/ToolDefinition.Serialization.cs @@ -6,48 +6,85 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { [PersistableModelProxy(typeof(UnknownAssistantToolDefinition))] - public partial class ToolDefinition : IJsonModel + public abstract partial class ToolDefinition : IJsonModel { - ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ToolDefinition)} does not support writing '{format}' format."); + } + if (_additionalBinaryDataProperties?.ContainsKey("type") != true) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) + { + if (ModelSerializationExtensions.IsSentinelValue(item.Value)) + { + continue; + } + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected virtual ToolDefinition 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(ToolDefinition)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeToolDefinition(document.RootElement, options); } - internal static ToolDefinition DeserializeToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static ToolDefinition DeserializeToolDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - if (element.TryGetProperty("type", out JsonElement discriminator)) + if (element.TryGetProperty("type"u8, out JsonElement discriminator)) { switch (discriminator.GetString()) { - case "code_interpreter": return CodeInterpreterToolDefinition.DeserializeCodeInterpreterToolDefinition(element, options); - case "file_search": return FileSearchToolDefinition.DeserializeFileSearchToolDefinition(element, options); - case "function": return FunctionToolDefinition.DeserializeFunctionToolDefinition(element, options); + case "code_interpreter": + return CodeInterpreterToolDefinition.DeserializeCodeInterpreterToolDefinition(element, options); + case "file_search": + return FileSearchToolDefinition.DeserializeFileSearchToolDefinition(element, options); + case "function": + return FunctionToolDefinition.DeserializeFunctionToolDefinition(element, options); } } return UnknownAssistantToolDefinition.DeserializeUnknownAssistantToolDefinition(element, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -57,15 +94,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ToolDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeToolDefinition(document.RootElement, options); } default: @@ -75,15 +113,20 @@ ToolDefinition IPersistableModel.Create(BinaryData data, ModelRe string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ToolDefinition FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ToolDefinition toolDefinition) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeToolDefinition(document.RootElement); + if (toolDefinition == null) + { + return null; + } + return BinaryContent.Create(toolDefinition, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ToolDefinition(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeToolDefinition(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ToolDefinition.cs b/src/Generated/Models/ToolDefinition.cs index 8f3a99763..a257dfa11 100644 --- a/src/Generated/Models/ToolDefinition.cs +++ b/src/Generated/Models/ToolDefinition.cs @@ -9,17 +9,20 @@ namespace OpenAI.Assistants { public abstract partial class ToolDefinition { - internal IDictionary SerializedAdditionalRawData { get; set; } - protected ToolDefinition() - { - } + private protected IDictionary _additionalBinaryDataProperties; - internal ToolDefinition(string type, IDictionary serializedAdditionalRawData) + internal ToolDefinition(string @type, IDictionary additionalBinaryDataProperties) { - Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = @type; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } internal string Type { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ToolOutput.Serialization.cs b/src/Generated/Models/ToolOutput.Serialization.cs index d4b3f7f17..552ade35f 100644 --- a/src/Generated/Models/ToolOutput.Serialization.cs +++ b/src/Generated/Models/ToolOutput.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ public partial class ToolOutput : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ToolOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("tool_call_id") != true && Optional.IsDefined(ToolCallId)) + if (Optional.IsDefined(ToolCallId) && _additionalBinaryDataProperties?.ContainsKey("tool_call_id") != true) { writer.WritePropertyName("tool_call_id"u8); writer.WriteStringValue(ToolCallId); } - if (SerializedAdditionalRawData?.ContainsKey("output") != true && Optional.IsDefined(Output)) + if (Optional.IsDefined(Output) && _additionalBinaryDataProperties?.ContainsKey("output") != true) { writer.WritePropertyName("output"u8); writer.WriteStringValue(Output); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOption } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOption #endif } } - writer.WriteEndObject(); } - ToolOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ToolOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ToolOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ToolOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeToolOutput(document.RootElement, options); } - internal static ToolOutput DeserializeToolOutput(JsonElement element, ModelReaderWriterOptions options = null) + internal static ToolOutput DeserializeToolOutput(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string toolCallId = default; string output = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("tool_call_id"u8)) + if (prop.NameEquals("tool_call_id"u8)) { - toolCallId = property.Value.GetString(); + toolCallId = prop.Value.GetString(); continue; } - if (property.NameEquals("output"u8)) + if (prop.NameEquals("output"u8)) { - output = property.Value.GetString(); + output = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ToolOutput(toolCallId, output, serializedAdditionalRawData); + return new ToolOutput(toolCallId, output, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) } } - ToolOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ToolOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ToolOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeToolOutput(document.RootElement, options); } default: @@ -130,15 +133,20 @@ ToolOutput IPersistableModel.Create(BinaryData data, ModelReaderWrit string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ToolOutput FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ToolOutput toolOutput) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeToolOutput(document.RootElement); + if (toolOutput == null) + { + return null; + } + return BinaryContent.Create(toolOutput, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ToolOutput(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeToolOutput(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ToolOutput.cs b/src/Generated/Models/ToolOutput.cs index 0e7b6441b..bcee7b40e 100644 --- a/src/Generated/Models/ToolOutput.cs +++ b/src/Generated/Models/ToolOutput.cs @@ -9,19 +9,27 @@ namespace OpenAI.Assistants { public partial class ToolOutput { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public ToolOutput() { } - internal ToolOutput(string toolCallId, string output, IDictionary serializedAdditionalRawData) + internal ToolOutput(string toolCallId, string output, IDictionary additionalBinaryDataProperties) { ToolCallId = toolCallId; Output = output; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string ToolCallId { get; set; } + public string Output { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/ToolResources.Serialization.cs b/src/Generated/Models/ToolResources.Serialization.cs index 75ceb9212..1bf9b3d4e 100644 --- a/src/Generated/Models/ToolResources.Serialization.cs +++ b/src/Generated/Models/ToolResources.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { @@ -14,26 +15,31 @@ public partial class ToolResources : IJsonModel { void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ToolResources)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code_interpreter") != true && Optional.IsDefined(CodeInterpreter)) + if (Optional.IsDefined(CodeInterpreter) && _additionalBinaryDataProperties?.ContainsKey("code_interpreter") != true) { writer.WritePropertyName("code_interpreter"u8); writer.WriteObjectValue(CodeInterpreter, options); } - if (SerializedAdditionalRawData?.ContainsKey("file_search") != true && Optional.IsDefined(FileSearch)) + if (Optional.IsDefined(FileSearch) && _additionalBinaryDataProperties?.ContainsKey("file_search") != true) { writer.WritePropertyName("file_search"u8); - SerializeFileSearch(writer, options); + this.SerializeFileSearch(writer, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,67 +56,63 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt #endif } } - writer.WriteEndObject(); } - ToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual ToolResources JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ToolResources)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeToolResources(document.RootElement, options); } - internal static ToolResources DeserializeToolResources(JsonElement element, ModelReaderWriterOptions options = null) + internal static ToolResources DeserializeToolResources(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } CodeInterpreterToolResources codeInterpreter = default; FileSearchToolResources fileSearch = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code_interpreter"u8)) + if (prop.NameEquals("code_interpreter"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - codeInterpreter = CodeInterpreterToolResources.DeserializeCodeInterpreterToolResources(property.Value, options); + codeInterpreter = CodeInterpreterToolResources.DeserializeCodeInterpreterToolResources(prop.Value, options); continue; } - if (property.NameEquals("file_search"u8)) + if (prop.NameEquals("file_search"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(property.Value, options); + fileSearch = FileSearchToolResources.DeserializeFileSearchToolResources(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new ToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + return new ToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -120,15 +122,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions optio } } - ToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual ToolResources 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeToolResources(document.RootElement, options); } default: @@ -138,15 +141,20 @@ ToolResources IPersistableModel.Create(BinaryData data, ModelRead string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ToolResources FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(ToolResources toolResources) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeToolResources(document.RootElement); + if (toolResources == null) + { + return null; + } + return BinaryContent.Create(toolResources, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator ToolResources(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeToolResources(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/ToolResources.cs b/src/Generated/Models/ToolResources.cs index 67b190971..5a2c85c10 100644 --- a/src/Generated/Models/ToolResources.cs +++ b/src/Generated/Models/ToolResources.cs @@ -9,13 +9,19 @@ namespace OpenAI.Assistants { public partial class ToolResources { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; - internal ToolResources(CodeInterpreterToolResources codeInterpreter, FileSearchToolResources fileSearch, IDictionary serializedAdditionalRawData) + internal ToolResources(CodeInterpreterToolResources codeInterpreter, FileSearchToolResources fileSearch, IDictionary additionalBinaryDataProperties) { CodeInterpreter = codeInterpreter; FileSearch = fileSearch; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; + } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } } } diff --git a/src/Generated/Models/TranscribedSegment.Serialization.cs b/src/Generated/Models/TranscribedSegment.Serialization.cs index 6af68a9e9..383ba7fd9 100644 --- a/src/Generated/Models/TranscribedSegment.Serialization.cs +++ b/src/Generated/Models/TranscribedSegment.Serialization.cs @@ -7,78 +7,88 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { - public partial struct TranscribedSegment : IJsonModel, IJsonModel + public readonly partial struct TranscribedSegment : IJsonModel, IJsonModel { + public TranscribedSegment() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + private 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(TranscribedSegment)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteNumberValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("seek") != true) + if (_additionalBinaryDataProperties?.ContainsKey("text") != true) { - writer.WritePropertyName("seek"u8); - writer.WriteNumberValue(SeekOffset); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + if (_additionalBinaryDataProperties?.ContainsKey("temperature") != true) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature); + } + if (_additionalBinaryDataProperties?.ContainsKey("compression_ratio") != true) + { + writer.WritePropertyName("compression_ratio"u8); + writer.WriteNumberValue(CompressionRatio); } - if (SerializedAdditionalRawData?.ContainsKey("start") != true) + if (_additionalBinaryDataProperties?.ContainsKey("start") != true) { writer.WritePropertyName("start"u8); writer.WriteNumberValue(Convert.ToDouble(StartTime.ToString("s\\.FFF"))); } - if (SerializedAdditionalRawData?.ContainsKey("end") != true) + if (_additionalBinaryDataProperties?.ContainsKey("end") != true) { writer.WritePropertyName("end"u8); writer.WriteNumberValue(Convert.ToDouble(EndTime.ToString("s\\.FFF"))); } - if (SerializedAdditionalRawData?.ContainsKey("text") != true) + if (_additionalBinaryDataProperties?.ContainsKey("seek") != true) { - writer.WritePropertyName("text"u8); - writer.WriteStringValue(Text); + writer.WritePropertyName("seek"u8); + writer.WriteNumberValue(SeekOffset); } - if (SerializedAdditionalRawData?.ContainsKey("tokens") != true) + if (_additionalBinaryDataProperties?.ContainsKey("tokens") != true) { writer.WritePropertyName("tokens"u8); writer.WriteStartArray(); - foreach (var item in TokenIds.Span) + foreach (int item in TokenIds.Span) { writer.WriteNumberValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("temperature") != true) - { - writer.WritePropertyName("temperature"u8); - writer.WriteNumberValue(Temperature); - } - if (SerializedAdditionalRawData?.ContainsKey("avg_logprob") != true) + if (_additionalBinaryDataProperties?.ContainsKey("avg_logprob") != true) { writer.WritePropertyName("avg_logprob"u8); writer.WriteNumberValue(AverageLogProbability); } - if (SerializedAdditionalRawData?.ContainsKey("compression_ratio") != true) - { - writer.WritePropertyName("compression_ratio"u8); - writer.WriteNumberValue(CompressionRatio); - } - if (SerializedAdditionalRawData?.ContainsKey("no_speech_prob") != true) + if (_additionalBinaryDataProperties?.ContainsKey("no_speech_prob") != true) { writer.WritePropertyName("no_speech_prob"u8); writer.WriteNumberValue(NoSpeechProbability); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -86,7 +96,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -95,129 +105,125 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit #endif } } - writer.WriteEndObject(); } - TranscribedSegment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + TranscribedSegment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + private TranscribedSegment JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(TranscribedSegment)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeTranscribedSegment(document.RootElement, options); } - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); - - object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); - - internal static TranscribedSegment DeserializeTranscribedSegment(JsonElement element, ModelReaderWriterOptions options = null) + internal static TranscribedSegment DeserializeTranscribedSegment(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - + if (element.ValueKind == JsonValueKind.Null) + { + return default; + } int id = default; - int seek = default; - TimeSpan start = default; - TimeSpan end = default; string text = default; - ReadOnlyMemory tokens = default; float temperature = default; - float avgLogprob = default; float compressionRatio = default; - float noSpeechProb = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + TimeSpan startTime = default; + TimeSpan endTime = default; + int seekOffset = default; + ReadOnlyMemory tokenIds = default; + float averageLogProbability = default; + float noSpeechProbability = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetInt32(); + id = prop.Value.GetInt32(); continue; } - if (property.NameEquals("seek"u8)) + if (prop.NameEquals("text"u8)) { - seek = property.Value.GetInt32(); + text = prop.Value.GetString(); continue; } - if (property.NameEquals("start"u8)) + if (prop.NameEquals("temperature"u8)) { - start = TimeSpan.FromSeconds(property.Value.GetDouble()); + temperature = prop.Value.GetSingle(); continue; } - if (property.NameEquals("end"u8)) + if (prop.NameEquals("compression_ratio"u8)) { - end = TimeSpan.FromSeconds(property.Value.GetDouble()); + compressionRatio = prop.Value.GetSingle(); continue; } - if (property.NameEquals("text"u8)) + if (prop.NameEquals("start"u8)) { - text = property.Value.GetString(); + startTime = TimeSpan.FromSeconds(prop.Value.GetDouble()); continue; } - if (property.NameEquals("tokens"u8)) + if (prop.NameEquals("end"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + endTime = TimeSpan.FromSeconds(prop.Value.GetDouble()); + continue; + } + if (prop.NameEquals("seek"u8)) + { + seekOffset = prop.Value.GetInt32(); + continue; + } + if (prop.NameEquals("tokens"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } int index = 0; - int[] array = new int[property.Value.GetArrayLength()]; - foreach (var item in property.Value.EnumerateArray()) + int[] array = new int[prop.Value.GetArrayLength()]; + foreach (var item in prop.Value.EnumerateArray()) { array[index] = item.GetInt32(); index++; } - tokens = new ReadOnlyMemory(array); - continue; - } - if (property.NameEquals("temperature"u8)) - { - temperature = property.Value.GetSingle(); + tokenIds = new ReadOnlyMemory(array); continue; } - if (property.NameEquals("avg_logprob"u8)) + if (prop.NameEquals("avg_logprob"u8)) { - avgLogprob = property.Value.GetSingle(); + averageLogProbability = prop.Value.GetSingle(); continue; } - if (property.NameEquals("compression_ratio"u8)) + if (prop.NameEquals("no_speech_prob"u8)) { - compressionRatio = property.Value.GetSingle(); - continue; - } - if (property.NameEquals("no_speech_prob"u8)) - { - noSpeechProb = property.Value.GetSingle(); + noSpeechProbability = prop.Value.GetSingle(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new TranscribedSegment( id, - seek, - start, - end, text, - tokens, temperature, - avgLogprob, compressionRatio, - noSpeechProb, - serializedAdditionalRawData); + startTime, + endTime, + seekOffset, + tokenIds, + averageLogProbability, + noSpeechProbability, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + private BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -227,15 +233,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - TranscribedSegment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + TranscribedSegment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + private TranscribedSegment 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeTranscribedSegment(document.RootElement, options); } default: @@ -245,21 +252,26 @@ TranscribedSegment IPersistableModel.Create(BinaryData data, string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); - - object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); - - internal static TranscribedSegment FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(TranscribedSegment transcribedSegment) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeTranscribedSegment(document.RootElement); + return BinaryContent.Create(transcribedSegment, ModelSerializationExtensions.WireOptions); } - internal BinaryContent ToBinaryContent() + public static explicit operator TranscribedSegment(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeTranscribedSegment(document.RootElement, ModelSerializationExtensions.WireOptions); } + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); + + object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); + + object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); } } diff --git a/src/Generated/Models/TranscribedSegment.cs b/src/Generated/Models/TranscribedSegment.cs index fb245f402..3b18d7b96 100644 --- a/src/Generated/Models/TranscribedSegment.cs +++ b/src/Generated/Models/TranscribedSegment.cs @@ -9,44 +9,45 @@ namespace OpenAI.Audio { public readonly partial struct TranscribedSegment { - internal TranscribedSegment(int id, int seekOffset, TimeSpan startTime, TimeSpan endTime, string text, ReadOnlyMemory tokenIds, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability) - { - Argument.AssertNotNull(text, nameof(text)); + private readonly IDictionary _additionalBinaryDataProperties; + internal TranscribedSegment(int id, string text, float temperature, float compressionRatio, TimeSpan startTime, TimeSpan endTime, int seekOffset, ReadOnlyMemory tokenIds, float averageLogProbability, float noSpeechProbability) + { Id = id; - SeekOffset = seekOffset; + Text = text; + Temperature = temperature; + CompressionRatio = compressionRatio; StartTime = startTime; EndTime = endTime; - Text = text; + SeekOffset = seekOffset; TokenIds = tokenIds; - Temperature = temperature; AverageLogProbability = averageLogProbability; - CompressionRatio = compressionRatio; NoSpeechProbability = noSpeechProbability; } - internal TranscribedSegment(int id, int seekOffset, TimeSpan startTime, TimeSpan endTime, string text, ReadOnlyMemory tokenIds, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IDictionary serializedAdditionalRawData) + internal TranscribedSegment(int id, string text, float temperature, float compressionRatio, TimeSpan startTime, TimeSpan endTime, int seekOffset, ReadOnlyMemory tokenIds, float averageLogProbability, float noSpeechProbability, IDictionary additionalBinaryDataProperties) { Id = id; - SeekOffset = seekOffset; + Text = text; + Temperature = temperature; + CompressionRatio = compressionRatio; StartTime = startTime; EndTime = endTime; - Text = text; + SeekOffset = seekOffset; TokenIds = tokenIds; - Temperature = temperature; AverageLogProbability = averageLogProbability; - CompressionRatio = compressionRatio; NoSpeechProbability = noSpeechProbability; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public TranscribedSegment() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int Id { get; } + public string Text { get; } + public float Temperature { get; } + public float CompressionRatio { get; } + + internal IDictionary SerializedAdditionalRawData => _additionalBinaryDataProperties; } } diff --git a/src/Generated/Models/TranscribedWord.Serialization.cs b/src/Generated/Models/TranscribedWord.Serialization.cs index c3e0cc0f4..28a1bc287 100644 --- a/src/Generated/Models/TranscribedWord.Serialization.cs +++ b/src/Generated/Models/TranscribedWord.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Audio { - public partial struct TranscribedWord : IJsonModel, IJsonModel + public readonly partial struct TranscribedWord : IJsonModel, IJsonModel { + public TranscribedWord() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + private 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(TranscribedWord)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("word") != true) + if (_additionalBinaryDataProperties?.ContainsKey("word") != true) { writer.WritePropertyName("word"u8); writer.WriteStringValue(Word); } - if (SerializedAdditionalRawData?.ContainsKey("start") != true) + if (_additionalBinaryDataProperties?.ContainsKey("start") != true) { writer.WritePropertyName("start"u8); writer.WriteNumberValue(Convert.ToDouble(StartTime.ToString("s\\.FFF"))); } - if (SerializedAdditionalRawData?.ContainsKey("end") != true) + if (_additionalBinaryDataProperties?.ContainsKey("end") != true) { writer.WritePropertyName("end"u8); writer.WriteNumberValue(Convert.ToDouble(EndTime.ToString("s\\.FFF"))); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO #endif } } - writer.WriteEndObject(); } - TranscribedWord IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + TranscribedWord IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + private TranscribedWord JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(TranscribedWord)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeTranscribedWord(document.RootElement, options); } - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); - - object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); - - internal static TranscribedWord DeserializeTranscribedWord(JsonElement element, ModelReaderWriterOptions options = null) + internal static TranscribedWord DeserializeTranscribedWord(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - + if (element.ValueKind == JsonValueKind.Null) + { + return default; + } string word = default; - TimeSpan start = default; - TimeSpan end = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + TimeSpan startTime = default; + TimeSpan endTime = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("word"u8)) + if (prop.NameEquals("word"u8)) { - word = property.Value.GetString(); + word = prop.Value.GetString(); continue; } - if (property.NameEquals("start"u8)) + if (prop.NameEquals("start"u8)) { - start = TimeSpan.FromSeconds(property.Value.GetDouble()); + startTime = TimeSpan.FromSeconds(prop.Value.GetDouble()); continue; } - if (property.NameEquals("end"u8)) + if (prop.NameEquals("end"u8)) { - end = TimeSpan.FromSeconds(property.Value.GetDouble()); + endTime = TimeSpan.FromSeconds(prop.Value.GetDouble()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new TranscribedWord(word, start, end, serializedAdditionalRawData); + return new TranscribedWord(word, startTime, endTime, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + private BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - TranscribedWord IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + TranscribedWord IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + private TranscribedWord 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeTranscribedWord(document.RootElement, options); } default: @@ -141,21 +148,26 @@ TranscribedWord IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); - - object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); - - internal static TranscribedWord FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(TranscribedWord transcribedWord) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeTranscribedWord(document.RootElement); + return BinaryContent.Create(transcribedWord, ModelSerializationExtensions.WireOptions); } - internal BinaryContent ToBinaryContent() + public static explicit operator TranscribedWord(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeTranscribedWord(document.RootElement, ModelSerializationExtensions.WireOptions); } + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)this).Write(writer, options); + + object IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)this).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ((IPersistableModel)this).Write(options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)this).GetFormatFromOptions(options); + + object IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel)this).Create(data, options); } } diff --git a/src/Generated/Models/TranscribedWord.cs b/src/Generated/Models/TranscribedWord.cs index 1ccbc4f85..c52ca8d49 100644 --- a/src/Generated/Models/TranscribedWord.cs +++ b/src/Generated/Models/TranscribedWord.cs @@ -9,27 +9,25 @@ namespace OpenAI.Audio { public readonly partial struct TranscribedWord { + private readonly IDictionary _additionalBinaryDataProperties; + internal TranscribedWord(string word, TimeSpan startTime, TimeSpan endTime) { - Argument.AssertNotNull(word, nameof(word)); - Word = word; StartTime = startTime; EndTime = endTime; } - internal TranscribedWord(string word, TimeSpan startTime, TimeSpan endTime, IDictionary serializedAdditionalRawData) + internal TranscribedWord(string word, TimeSpan startTime, TimeSpan endTime, IDictionary additionalBinaryDataProperties) { Word = word; StartTime = startTime; EndTime = endTime; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - public TranscribedWord() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Word { get; } + + internal IDictionary SerializedAdditionalRawData => _additionalBinaryDataProperties; } } diff --git a/src/Generated/Models/UnknownAssistantToolDefinition.Serialization.cs b/src/Generated/Models/UnknownAssistantToolDefinition.Serialization.cs index b26d26d05..929e01eb3 100644 --- a/src/Generated/Models/UnknownAssistantToolDefinition.Serialization.cs +++ b/src/Generated/Models/UnknownAssistantToolDefinition.Serialization.cs @@ -3,59 +3,70 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownAssistantToolDefinition : IJsonModel { - ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + internal UnknownAssistantToolDefinition() { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + } + + 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(ToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ToolDefinition)} does not support writing '{format}' format."); } + base.JsonModelWriteCore(writer, options); + } + + ToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + protected override ToolDefinition 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(ToolDefinition)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeToolDefinition(document.RootElement, options); } - internal static UnknownAssistantToolDefinition DeserializeUnknownAssistantToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownAssistantToolDefinition DeserializeUnknownAssistantToolDefinition(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownAssistantToolDefinition(type, serializedAdditionalRawData); + return new UnknownAssistantToolDefinition(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -65,15 +76,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ToolDefinition 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeToolDefinition(document.RootElement, options); } default: @@ -82,16 +94,5 @@ ToolDefinition IPersistableModel.Create(BinaryData data, ModelRe } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownAssistantToolDefinition FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownAssistantToolDefinition(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownAssistantToolDefinition.cs b/src/Generated/Models/UnknownAssistantToolDefinition.cs index ca5c335e1..9241104cc 100644 --- a/src/Generated/Models/UnknownAssistantToolDefinition.cs +++ b/src/Generated/Models/UnknownAssistantToolDefinition.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownAssistantToolDefinition : ToolDefinition { - internal UnknownAssistantToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownAssistantToolDefinition() + internal UnknownAssistantToolDefinition(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.Serialization.cs b/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.Serialization.cs index 7e77542bf..18646e9bd 100644 --- a/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.Serialization.cs +++ b/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class UnknownCreateFineTuningJobRequestIntegration : IJsonModel { + internal UnknownCreateFineTuningJobRequestIntegration() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(FineTuningIntegration)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - FineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override FineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(FineTuningIntegration)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeFineTuningIntegration(document.RootElement, options); } - internal static UnknownCreateFineTuningJobRequestIntegration DeserializeUnknownCreateFineTuningJobRequestIntegration(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownCreateFineTuningJobRequestIntegration DeserializeUnknownCreateFineTuningJobRequestIntegration(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownCreateFineTuningJobRequestIntegration(type, serializedAdditionalRawData); + return new UnknownCreateFineTuningJobRequestIntegration(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - FineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + FineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override FineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeFineTuningIntegration(document.RootElement, options); } default: @@ -118,16 +101,5 @@ FineTuningIntegration IPersistableModel.Create(BinaryData } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownCreateFineTuningJobRequestIntegration FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownCreateFineTuningJobRequestIntegration(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.cs b/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.cs index cbf12dee8..b883407b7 100644 --- a/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.cs +++ b/src/Generated/Models/UnknownCreateFineTuningJobRequestIntegration.cs @@ -9,11 +9,7 @@ namespace OpenAI.FineTuning { internal partial class UnknownCreateFineTuningJobRequestIntegration : FineTuningIntegration { - internal UnknownCreateFineTuningJobRequestIntegration(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownCreateFineTuningJobRequestIntegration() + internal UnknownCreateFineTuningJobRequestIntegration(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownFineTuningIntegration.Serialization.cs b/src/Generated/Models/UnknownFineTuningIntegration.Serialization.cs index dd39b6cd8..f38d39bce 100644 --- a/src/Generated/Models/UnknownFineTuningIntegration.Serialization.cs +++ b/src/Generated/Models/UnknownFineTuningIntegration.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class UnknownFineTuningIntegration : IJsonModel { + internal UnknownFineTuningIntegration() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalFineTuningIntegration)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalFineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalFineTuningIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalFineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalFineTuningIntegration)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalFineTuningIntegration(document.RootElement, options); } - internal static UnknownFineTuningIntegration DeserializeUnknownFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownFineTuningIntegration DeserializeUnknownFineTuningIntegration(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownFineTuningIntegration(type, serializedAdditionalRawData); + return new UnknownFineTuningIntegration(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWri } } - InternalFineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalFineTuningIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalFineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalFineTuningIntegration(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalFineTuningIntegration IPersistableModel.C } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownFineTuningIntegration FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownFineTuningIntegration(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownFineTuningIntegration.cs b/src/Generated/Models/UnknownFineTuningIntegration.cs index 8252f2576..8e6fd4d22 100644 --- a/src/Generated/Models/UnknownFineTuningIntegration.cs +++ b/src/Generated/Models/UnknownFineTuningIntegration.cs @@ -9,11 +9,7 @@ namespace OpenAI.FineTuning { internal partial class UnknownFineTuningIntegration : InternalFineTuningIntegration { - internal UnknownFineTuningIntegration(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownFineTuningIntegration() + internal UnknownFineTuningIntegration(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.Serialization.cs b/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.Serialization.cs index b0a6d9584..f1faf7745 100644 --- a/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.Serialization.cs +++ b/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownMessageContentTextObjectAnnotation : IJsonModel { + internal UnknownMessageContentTextObjectAnnotation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageContentTextObjectAnnotation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalMessageContentTextObjectAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageContentTextObjectAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalMessageContentTextObjectAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageContentTextObjectAnnotation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement, options); } - internal static UnknownMessageContentTextObjectAnnotation DeserializeUnknownMessageContentTextObjectAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownMessageContentTextObjectAnnotation DeserializeUnknownMessageContentTextObjectAnnotation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownMessageContentTextObjectAnnotation(type, serializedAdditionalRawData); + return new UnknownMessageContentTextObjectAnnotation(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(M } } - InternalMessageContentTextObjectAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageContentTextObjectAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalMessageContentTextObjectAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageContentTextObjectAnnotation(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalMessageContentTextObjectAnnotation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownMessageContentTextObjectAnnotation FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownMessageContentTextObjectAnnotation(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.cs b/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.cs index b5561f7cd..cdc91cb65 100644 --- a/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.cs +++ b/src/Generated/Models/UnknownMessageContentTextObjectAnnotation.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownMessageContentTextObjectAnnotation : InternalMessageContentTextObjectAnnotation { - internal UnknownMessageContentTextObjectAnnotation(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownMessageContentTextObjectAnnotation() + internal UnknownMessageContentTextObjectAnnotation(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownMessageDeltaContent.Serialization.cs b/src/Generated/Models/UnknownMessageDeltaContent.Serialization.cs index f4570019f..4b88fb791 100644 --- a/src/Generated/Models/UnknownMessageDeltaContent.Serialization.cs +++ b/src/Generated/Models/UnknownMessageDeltaContent.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownMessageDeltaContent : IJsonModel { + internal UnknownMessageDeltaContent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaContent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalMessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaContent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaContent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaContent(document.RootElement, options); } - internal static UnknownMessageDeltaContent DeserializeUnknownMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownMessageDeltaContent DeserializeUnknownMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownMessageDeltaContent(type, serializedAdditionalRawData); + return new UnknownMessageDeltaContent(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalMessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaContent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaContent(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalMessageDeltaContent IPersistableModel.Creat } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownMessageDeltaContent FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownMessageDeltaContent(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownMessageDeltaContent.cs b/src/Generated/Models/UnknownMessageDeltaContent.cs index a33b74454..add4753cc 100644 --- a/src/Generated/Models/UnknownMessageDeltaContent.cs +++ b/src/Generated/Models/UnknownMessageDeltaContent.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownMessageDeltaContent : InternalMessageDeltaContent { - internal UnknownMessageDeltaContent(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownMessageDeltaContent() + internal UnknownMessageDeltaContent(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.Serialization.cs b/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.Serialization.cs index 1fda24c5c..fd95ef989 100644 --- a/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.Serialization.cs +++ b/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownMessageDeltaTextContentAnnotation : IJsonModel { + internal UnknownMessageDeltaTextContentAnnotation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalMessageDeltaTextContentAnnotation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalMessageDeltaTextContentAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalMessageDeltaTextContentAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalMessageDeltaTextContentAnnotation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalMessageDeltaTextContentAnnotation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement, options); } - internal static UnknownMessageDeltaTextContentAnnotation DeserializeUnknownMessageDeltaTextContentAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownMessageDeltaTextContentAnnotation DeserializeUnknownMessageDeltaTextContentAnnotation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownMessageDeltaTextContentAnnotation(type, serializedAdditionalRawData); + return new UnknownMessageDeltaTextContentAnnotation(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(Mo } } - InternalMessageDeltaTextContentAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalMessageDeltaTextContentAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalMessageDeltaTextContentAnnotation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalMessageDeltaTextContentAnnotation(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalMessageDeltaTextContentAnnotation IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownMessageDeltaTextContentAnnotation FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownMessageDeltaTextContentAnnotation(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.cs b/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.cs index d6f17c1ab..b72e96ef1 100644 --- a/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.cs +++ b/src/Generated/Models/UnknownMessageDeltaTextContentAnnotation.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownMessageDeltaTextContentAnnotation : InternalMessageDeltaTextContentAnnotation { - internal UnknownMessageDeltaTextContentAnnotation(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownMessageDeltaTextContentAnnotation() + internal UnknownMessageDeltaTextContentAnnotation(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeClientEvent.Serialization.cs b/src/Generated/Models/UnknownRealtimeClientEvent.Serialization.cs index e24b6002b..16f2281c8 100644 --- a/src/Generated/Models/UnknownRealtimeClientEvent.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeClientEvent.Serialization.cs @@ -3,106 +3,83 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeClientEvent : IJsonModel { + internal UnknownRealtimeClientEvent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeClientEvent)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true && Optional.IsDefined(EventId)) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeClientEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeClientEvent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeClientEvent JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeClientEvent)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeClientEvent(document.RootElement, options); } - internal static UnknownRealtimeClientEvent DeserializeUnknownRealtimeClientEvent(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeClientEvent DeserializeUnknownRealtimeClientEvent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeClientEventType type = "Unknown"; + InternalRealtimeClientEventType kind = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeClientEventType(property.Value.GetString()); + kind = new InternalRealtimeClientEventType(prop.Value.GetString()); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("event_id"u8)) { - eventId = property.Value.GetString(); + eventId = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeClientEvent(type, eventId, serializedAdditionalRawData); + return new UnknownRealtimeClientEvent(kind, eventId, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +89,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - InternalRealtimeClientEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeClientEvent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalRealtimeClientEvent 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeClientEvent(document.RootElement, options); } default: @@ -129,16 +107,5 @@ InternalRealtimeClientEvent IPersistableModel.Creat } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeClientEvent FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeClientEvent(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeClientEvent.cs b/src/Generated/Models/UnknownRealtimeClientEvent.cs index 7c89c1f34..9dc2bb8e5 100644 --- a/src/Generated/Models/UnknownRealtimeClientEvent.cs +++ b/src/Generated/Models/UnknownRealtimeClientEvent.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeClientEvent : InternalRealtimeClientEvent { - internal UnknownRealtimeClientEvent(InternalRealtimeClientEventType kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeClientEvent() + internal UnknownRealtimeClientEvent(InternalRealtimeClientEventType kind, string eventId, IDictionary additionalBinaryDataProperties) : base(kind != default ? kind : "unknown", eventId, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeContentPart.Serialization.cs b/src/Generated/Models/UnknownRealtimeContentPart.Serialization.cs index acc6b86e1..28867bbbd 100644 --- a/src/Generated/Models/UnknownRealtimeContentPart.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeContentPart.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeContentPart : IJsonModel { + internal UnknownRealtimeContentPart() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationContentPart)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationContentPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationContentPart JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationContentPart)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationContentPart(document.RootElement, options); } - internal static UnknownRealtimeContentPart DeserializeUnknownRealtimeContentPart(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeContentPart DeserializeUnknownRealtimeContentPart(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationContentPartKind type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationContentPartKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new ConversationContentPartKind(property.Value.GetString()); + kind = new ConversationContentPartKind(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeContentPart(type, serializedAdditionalRawData); + return new UnknownRealtimeContentPart(kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - ConversationContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationContentPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationContentPart 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationContentPart(document.RootElement, options); } default: @@ -118,16 +101,5 @@ ConversationContentPart IPersistableModel.Create(Binary } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeContentPart FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeContentPart(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeContentPart.cs b/src/Generated/Models/UnknownRealtimeContentPart.cs index 8c332b466..a46fcddcf 100644 --- a/src/Generated/Models/UnknownRealtimeContentPart.cs +++ b/src/Generated/Models/UnknownRealtimeContentPart.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeContentPart : ConversationContentPart { - internal UnknownRealtimeContentPart(ConversationContentPartKind kind, IDictionary serializedAdditionalRawData) : base(kind, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeContentPart() + internal UnknownRealtimeContentPart(ConversationContentPartKind kind, IDictionary additionalBinaryDataProperties) : base(kind != default ? kind : "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeRequestItem.Serialization.cs b/src/Generated/Models/UnknownRealtimeRequestItem.Serialization.cs index a1acf18bf..c32837795 100644 --- a/src/Generated/Models/UnknownRealtimeRequestItem.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeRequestItem.Serialization.cs @@ -3,106 +3,83 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeRequestItem : IJsonModel { + internal UnknownRealtimeRequestItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationItem(document.RootElement, options); } - internal static UnknownRealtimeRequestItem DeserializeUnknownRealtimeRequestItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeRequestItem DeserializeUnknownRealtimeRequestItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - InternalRealtimeItemType type = "Unknown"; + InternalRealtimeItemType @type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeRequestItem(type, id, serializedAdditionalRawData); + return new UnknownRealtimeRequestItem(@type, id, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +89,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ConversationItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationItem(document.RootElement, options); } default: @@ -129,16 +107,5 @@ ConversationItem IPersistableModel.Create(BinaryData data, Mod } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeRequestItem FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeRequestItem(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeRequestItem.cs b/src/Generated/Models/UnknownRealtimeRequestItem.cs index c917c700c..eceb1f9cd 100644 --- a/src/Generated/Models/UnknownRealtimeRequestItem.cs +++ b/src/Generated/Models/UnknownRealtimeRequestItem.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeRequestItem : ConversationItem { - internal UnknownRealtimeRequestItem(InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData) : base(type, id, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeRequestItem() + internal UnknownRealtimeRequestItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties) : base(@type != default ? @type : "unknown", id, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeRequestMessageItem.Serialization.cs b/src/Generated/Models/UnknownRealtimeRequestMessageItem.Serialization.cs new file mode 100644 index 000000000..bf48837ab --- /dev/null +++ b/src/Generated/Models/UnknownRealtimeRequestMessageItem.Serialization.cs @@ -0,0 +1,127 @@ +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using OpenAI; + +namespace OpenAI.RealtimeConversation +{ + internal partial class UnknownRealtimeRequestMessageItem : IJsonModel + { + internal UnknownRealtimeRequestMessageItem() + { + } + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeRequestMessageItem)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + } + + InternalRealtimeRequestMessageItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (UnknownRealtimeRequestMessageItem)JsonModelCreateCore(ref reader, options); + + protected override ConversationItem 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(InternalRealtimeRequestMessageItem)} does not support reading '{format}' format."); + } + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInternalRealtimeRequestMessageItem(document.RootElement, options); + } + + internal static UnknownRealtimeRequestMessageItem DeserializeUnknownRealtimeRequestMessageItem(JsonElement element, ModelReaderWriterOptions options) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InternalRealtimeItemType @type = default; + string id = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + ConversationMessageRole role = default; + ConversationItemStatus? status = default; + foreach (var prop in element.EnumerateObject()) + { + if (prop.NameEquals("type"u8)) + { + @type = new InternalRealtimeItemType(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("id"u8)) + { + id = prop.Value.GetString(); + continue; + } + if (prop.NameEquals("role"u8)) + { + role = new ConversationMessageRole(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("status"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new ConversationItemStatus(prop.Value.GetString()); + continue; + } + if (true) + { + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); + } + } + return new UnknownRealtimeRequestMessageItem(@type, id, additionalBinaryDataProperties, role, status); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + + 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); + default: + throw new FormatException($"The model {nameof(InternalRealtimeRequestMessageItem)} does not support writing '{options.Format}' format."); + } + } + + InternalRealtimeRequestMessageItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (UnknownRealtimeRequestMessageItem)PersistableModelCreateCore(data, options); + + protected override ConversationItem 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)) + { + return DeserializeInternalRealtimeRequestMessageItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InternalRealtimeRequestMessageItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/src/Generated/Models/UnknownRealtimeRequestMessageItem.cs b/src/Generated/Models/UnknownRealtimeRequestMessageItem.cs new file mode 100644 index 000000000..7d3958548 --- /dev/null +++ b/src/Generated/Models/UnknownRealtimeRequestMessageItem.cs @@ -0,0 +1,16 @@ +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace OpenAI.RealtimeConversation +{ + internal partial class UnknownRealtimeRequestMessageItem : InternalRealtimeRequestMessageItem + { + internal UnknownRealtimeRequestMessageItem(InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties, ConversationMessageRole role, ConversationItemStatus? status) : base(@type != default ? @type : "unknown", id, additionalBinaryDataProperties, role != default ? role : "unknown", status) + { + } + } +} diff --git a/src/Generated/Models/UnknownRealtimeResponseItem.Serialization.cs b/src/Generated/Models/UnknownRealtimeResponseItem.Serialization.cs index 7370fee72..f618f94fd 100644 --- a/src/Generated/Models/UnknownRealtimeResponseItem.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeResponseItem.Serialization.cs @@ -3,129 +3,94 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeResponseItem : IJsonModel { + internal UnknownRealtimeResponseItem() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeResponseItem)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - if (Id != null) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - else - { - writer.WriteNull("id"); - } - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeResponseItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeResponseItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeResponseItem JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeResponseItem)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeResponseItem(document.RootElement, options); } - internal static UnknownRealtimeResponseItem DeserializeUnknownRealtimeResponseItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeResponseItem DeserializeUnknownRealtimeResponseItem(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } InternalRealtimeResponseItemObject @object = default; - InternalRealtimeItemType type = "Unknown"; + InternalRealtimeItemType @type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalRealtimeResponseItemObject(property.Value.GetString()); + @object = new InternalRealtimeResponseItemObject(prop.Value.GetString()); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new InternalRealtimeItemType(property.Value.GetString()); + @type = new InternalRealtimeItemType(prop.Value.GetString()); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("id"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { id = null; continue; } - id = property.Value.GetString(); + id = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeResponseItem(@object, type, id, serializedAdditionalRawData); + return new UnknownRealtimeResponseItem(@object, @type, id, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -135,15 +100,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - InternalRealtimeResponseItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeResponseItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalRealtimeResponseItem 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeResponseItem(document.RootElement, options); } default: @@ -152,16 +118,5 @@ InternalRealtimeResponseItem IPersistableModel.Cre } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeResponseItem FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeResponseItem(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeResponseItem.cs b/src/Generated/Models/UnknownRealtimeResponseItem.cs index 9823a49de..bb08f7ea4 100644 --- a/src/Generated/Models/UnknownRealtimeResponseItem.cs +++ b/src/Generated/Models/UnknownRealtimeResponseItem.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeResponseItem : InternalRealtimeResponseItem { - internal UnknownRealtimeResponseItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType type, string id, IDictionary serializedAdditionalRawData) : base(@object, type, id, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeResponseItem() + internal UnknownRealtimeResponseItem(InternalRealtimeResponseItemObject @object, InternalRealtimeItemType @type, string id, IDictionary additionalBinaryDataProperties) : base(@object, @type != default ? @type : "unknown", id, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeResponseStatusDetails.Serialization.cs b/src/Generated/Models/UnknownRealtimeResponseStatusDetails.Serialization.cs index 2f8fc68e0..21fc7644a 100644 --- a/src/Generated/Models/UnknownRealtimeResponseStatusDetails.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeResponseStatusDetails.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeResponseStatusDetails : IJsonModel { + internal UnknownRealtimeResponseStatusDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationStatusDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(StatusKind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationStatusDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationStatusDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationStatusDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationStatusDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationStatusDetails(document.RootElement, options); } - internal static UnknownRealtimeResponseStatusDetails DeserializeUnknownRealtimeResponseStatusDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeResponseStatusDetails DeserializeUnknownRealtimeResponseStatusDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationStatus type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationStatus statusKind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new ConversationStatus(property.Value.GetString()); + statusKind = new ConversationStatus(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeResponseStatusDetails(type, serializedAdditionalRawData); + return new UnknownRealtimeResponseStatusDetails(statusKind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - ConversationStatusDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationStatusDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationStatusDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationStatusDetails(document.RootElement, options); } default: @@ -118,16 +101,5 @@ ConversationStatusDetails IPersistableModel.Create(Bi } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeResponseStatusDetails FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeResponseStatusDetails(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeResponseStatusDetails.cs b/src/Generated/Models/UnknownRealtimeResponseStatusDetails.cs index c21984b9e..0bbcb1f2a 100644 --- a/src/Generated/Models/UnknownRealtimeResponseStatusDetails.cs +++ b/src/Generated/Models/UnknownRealtimeResponseStatusDetails.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeResponseStatusDetails : ConversationStatusDetails { - internal UnknownRealtimeResponseStatusDetails(ConversationStatus statusKind, IDictionary serializedAdditionalRawData) : base(statusKind, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeResponseStatusDetails() + internal UnknownRealtimeResponseStatusDetails(ConversationStatus statusKind, IDictionary additionalBinaryDataProperties) : base(statusKind != default ? statusKind : "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeServerEvent.Serialization.cs b/src/Generated/Models/UnknownRealtimeServerEvent.Serialization.cs index 0b87f20af..aa48c7391 100644 --- a/src/Generated/Models/UnknownRealtimeServerEvent.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeServerEvent.Serialization.cs @@ -3,106 +3,83 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeServerEvent : IJsonModel { + internal UnknownRealtimeServerEvent() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationUpdate)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("event_id") != true) - { - writer.WritePropertyName("event_id"u8); - writer.WriteStringValue(EventId); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationUpdate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationUpdate JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationUpdate)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeConversationUpdate(document.RootElement, options); + return ConversationUpdate.DeserializeConversationUpdate(document.RootElement, options); } - internal static UnknownRealtimeServerEvent DeserializeUnknownRealtimeServerEvent(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeServerEvent DeserializeUnknownRealtimeServerEvent(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationUpdateKind type = default; string eventId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationUpdateKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("event_id"u8)) { - type = property.Value.GetString().ToConversationUpdateKind(); + eventId = prop.Value.GetString(); continue; } - if (property.NameEquals("event_id"u8)) + if (prop.NameEquals("type"u8)) { - eventId = property.Value.GetString(); + kind = prop.Value.GetString().ToConversationUpdateKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeServerEvent(type, eventId, serializedAdditionalRawData); + return new UnknownRealtimeServerEvent(eventId, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,16 +89,17 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions } } - ConversationUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationUpdate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationUpdate 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeConversationUpdate(document.RootElement, options); + return ConversationUpdate.DeserializeConversationUpdate(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ConversationUpdate)} does not support reading '{options.Format}' format."); @@ -129,16 +107,5 @@ ConversationUpdate IPersistableModel.Create(BinaryData data, } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeServerEvent FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeServerEvent(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeServerEvent.cs b/src/Generated/Models/UnknownRealtimeServerEvent.cs index 4954c31c3..d2e999978 100644 --- a/src/Generated/Models/UnknownRealtimeServerEvent.cs +++ b/src/Generated/Models/UnknownRealtimeServerEvent.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeServerEvent : ConversationUpdate { - internal UnknownRealtimeServerEvent(ConversationUpdateKind kind, string eventId, IDictionary serializedAdditionalRawData) : base(kind, eventId, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeServerEvent() + internal UnknownRealtimeServerEvent(string eventId, RealtimeConversation.ConversationUpdateKind kind, IDictionary additionalBinaryDataProperties) : base(eventId, kind, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeTool.Serialization.cs b/src/Generated/Models/UnknownRealtimeTool.Serialization.cs index 0a570abc1..bbf65b2f3 100644 --- a/src/Generated/Models/UnknownRealtimeTool.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeTool.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeTool : IJsonModel { + internal UnknownRealtimeTool() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationTool)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationTool IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationTool JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationTool)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeConversationTool(document.RootElement, options); } - internal static UnknownRealtimeTool DeserializeUnknownRealtimeTool(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeTool DeserializeUnknownRealtimeTool(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationToolKind type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationToolKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new ConversationToolKind(property.Value.GetString()); + kind = new ConversationToolKind(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeTool(type, serializedAdditionalRawData); + return new UnknownRealtimeTool(kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions op } } - ConversationTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationTool IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationTool 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeConversationTool(document.RootElement, options); } default: @@ -118,16 +101,5 @@ ConversationTool IPersistableModel.Create(BinaryData data, Mod } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeTool FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeTool(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeTool.cs b/src/Generated/Models/UnknownRealtimeTool.cs index c71d8e5c5..83eecfa1d 100644 --- a/src/Generated/Models/UnknownRealtimeTool.cs +++ b/src/Generated/Models/UnknownRealtimeTool.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeTool : ConversationTool { - internal UnknownRealtimeTool(ConversationToolKind kind, IDictionary serializedAdditionalRawData) : base(kind, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeTool() + internal UnknownRealtimeTool(ConversationToolKind kind, IDictionary additionalBinaryDataProperties) : base(kind != default ? kind : "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeToolChoiceObject.Serialization.cs b/src/Generated/Models/UnknownRealtimeToolChoiceObject.Serialization.cs index 8675b9116..ced86e48a 100644 --- a/src/Generated/Models/UnknownRealtimeToolChoiceObject.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeToolChoiceObject.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeToolChoiceObject : IJsonModel { + internal UnknownRealtimeToolChoiceObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRealtimeToolChoiceObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRealtimeToolChoiceObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRealtimeToolChoiceObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalRealtimeToolChoiceObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRealtimeToolChoiceObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRealtimeToolChoiceObject(document.RootElement, options); } - internal static UnknownRealtimeToolChoiceObject DeserializeUnknownRealtimeToolChoiceObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeToolChoiceObject DeserializeUnknownRealtimeToolChoiceObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationToolKind type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + ConversationToolKind @type = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = new ConversationToolKind(property.Value.GetString()); + @type = new ConversationToolKind(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeToolChoiceObject(type, serializedAdditionalRawData); + return new UnknownRealtimeToolChoiceObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReader } } - InternalRealtimeToolChoiceObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRealtimeToolChoiceObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalRealtimeToolChoiceObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRealtimeToolChoiceObject(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalRealtimeToolChoiceObject IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeToolChoiceObject FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeToolChoiceObject(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeToolChoiceObject.cs b/src/Generated/Models/UnknownRealtimeToolChoiceObject.cs index a3fa5eb28..b98513580 100644 --- a/src/Generated/Models/UnknownRealtimeToolChoiceObject.cs +++ b/src/Generated/Models/UnknownRealtimeToolChoiceObject.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeToolChoiceObject : InternalRealtimeToolChoiceObject { - internal UnknownRealtimeToolChoiceObject(ConversationToolKind type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeToolChoiceObject() + internal UnknownRealtimeToolChoiceObject(ConversationToolKind @type, IDictionary additionalBinaryDataProperties) : base(@type != default ? @type : "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRealtimeTurnDetection.Serialization.cs b/src/Generated/Models/UnknownRealtimeTurnDetection.Serialization.cs index 3f2fd3a69..893f07b6a 100644 --- a/src/Generated/Models/UnknownRealtimeTurnDetection.Serialization.cs +++ b/src/Generated/Models/UnknownRealtimeTurnDetection.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeTurnDetection : IJsonModel { + internal UnknownRealtimeTurnDetection() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(ConversationTurnDetectionOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - ConversationTurnDetectionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ConversationTurnDetectionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override ConversationTurnDetectionOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(ConversationTurnDetectionOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeConversationTurnDetectionOptions(document.RootElement, options); + return ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(document.RootElement, options); } - internal static UnknownRealtimeTurnDetection DeserializeUnknownRealtimeTurnDetection(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRealtimeTurnDetection DeserializeUnknownRealtimeTurnDetection(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - ConversationTurnDetectionKind type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + RealtimeConversation.ConversationTurnDetectionKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString().ToConversationTurnDetectionKind(); + kind = prop.Value.GetString().ToConversationTurnDetectionKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRealtimeTurnDetection(type, serializedAdditionalRawData); + return new UnknownRealtimeTurnDetection(kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,16 +83,17 @@ BinaryData IPersistableModel.Write(ModelReader } } - ConversationTurnDetectionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + ConversationTurnDetectionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override ConversationTurnDetectionOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeConversationTurnDetectionOptions(document.RootElement, options); + return ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(document.RootElement, options); } default: throw new FormatException($"The model {nameof(ConversationTurnDetectionOptions)} does not support reading '{options.Format}' format."); @@ -118,16 +101,5 @@ ConversationTurnDetectionOptions IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRealtimeTurnDetection FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRealtimeTurnDetection(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRealtimeTurnDetection.cs b/src/Generated/Models/UnknownRealtimeTurnDetection.cs index 5234828ae..e5706b570 100644 --- a/src/Generated/Models/UnknownRealtimeTurnDetection.cs +++ b/src/Generated/Models/UnknownRealtimeTurnDetection.cs @@ -9,11 +9,7 @@ namespace OpenAI.RealtimeConversation { internal partial class UnknownRealtimeTurnDetection : ConversationTurnDetectionOptions { - internal UnknownRealtimeTurnDetection(ConversationTurnDetectionKind kind, IDictionary serializedAdditionalRawData) : base(kind, serializedAdditionalRawData) - { - } - - internal UnknownRealtimeTurnDetection() + internal UnknownRealtimeTurnDetection(RealtimeConversation.ConversationTurnDetectionKind kind, IDictionary additionalBinaryDataProperties) : base(kind, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetails.Serialization.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetails.Serialization.cs index 287960a64..1001a346d 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetails.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetails.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetails : IJsonModel { + internal UnknownRunStepDeltaStepDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRunStepDeltaStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetails(document.RootElement, options); } - internal static UnknownRunStepDeltaStepDetails DeserializeUnknownRunStepDeltaStepDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepDeltaStepDetails DeserializeUnknownRunStepDeltaStepDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepDeltaStepDetails(type, serializedAdditionalRawData); + return new UnknownRunStepDeltaStepDetails(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - InternalRunStepDeltaStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetails(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalRunStepDeltaStepDetails IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepDeltaStepDetails FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepDeltaStepDetails(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetails.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetails.cs index d56091482..7db2d8484 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetails.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetails.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetails : InternalRunStepDeltaStepDetails { - internal UnknownRunStepDeltaStepDetails(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRunStepDeltaStepDetails() + internal UnknownRunStepDeltaStepDetails(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs index 4790ac0f2..53787e08c 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject : IJsonModel { + internal UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepUpdateCodeInterpreterOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - RunStepUpdateCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepUpdateCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override RunStepUpdateCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepUpdateCodeInterpreterOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement, options); } - internal static UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject DeserializeUnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject DeserializeUnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(type, serializedAdditionalRawData); + return new UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelRead } } - RunStepUpdateCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepUpdateCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override RunStepUpdateCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepUpdateCodeInterpreterOutput(document.RootElement, options); } default: @@ -118,16 +101,5 @@ RunStepUpdateCodeInterpreterOutput IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs index d57ff0397..714634424 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject : RunStepUpdateCodeInterpreterOutput { - internal UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject() + internal UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs index b5bcbda2c..9ca843d25 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject : IJsonModel { + internal UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement, options); } - internal static UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject DeserializeUnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject DeserializeUnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(type, serializedAdditionalRawData); + return new UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeInternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement, options); } default: @@ -118,16 +101,5 @@ InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject IPersistableModel< } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs index 5a0c3e670..2cb16e57d 100644 --- a/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs +++ b/src/Generated/Models/UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject : InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject { - internal UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject() + internal UnknownRunStepDeltaStepDetailsToolCallsObjectToolCallsObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs b/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs index 86648d23b..ca2a237bd 100644 --- a/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject : IJsonModel { + internal UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepCodeInterpreterOutput)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - RunStepCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override RunStepCodeInterpreterOutput JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepCodeInterpreterOutput)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepCodeInterpreterOutput(document.RootElement, options); } - internal static UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject DeserializeUnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject DeserializeUnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(type, serializedAdditionalRawData); + return new UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrit } } - RunStepCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override RunStepCodeInterpreterOutput 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepCodeInterpreterOutput(document.RootElement, options); } default: @@ -118,16 +101,5 @@ RunStepCodeInterpreterOutput IPersistableModel.Cre } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs b/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs index 210c6b0af..b4c3c2632 100644 --- a/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs +++ b/src/Generated/Models/UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject : RunStepCodeInterpreterOutput { - internal UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject() + internal UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.Serialization.cs b/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.Serialization.cs index 600a3eed3..66a751e3a 100644 --- a/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.Serialization.cs @@ -3,106 +3,83 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepDetailsToolCallsObjectToolCallsObject : IJsonModel { + internal UnknownRunStepDetailsToolCallsObjectToolCallsObject() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepToolCall)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Kind.ToSerialString()); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - RunStepToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override RunStepToolCall JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepToolCall)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepToolCall(document.RootElement, options); } - internal static UnknownRunStepDetailsToolCallsObjectToolCallsObject DeserializeUnknownRunStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepDetailsToolCallsObjectToolCallsObject DeserializeUnknownRunStepDetailsToolCallsObjectToolCallsObject(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - RunStepToolCallKind type = default; string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + Assistants.RunStepToolCallKind kind = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("id"u8)) { - type = property.Value.GetString().ToRunStepToolCallKind(); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) + if (prop.NameEquals("type"u8)) { - id = property.Value.GetString(); + kind = prop.Value.GetString().ToRunStepToolCallKind(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepDetailsToolCallsObjectToolCallsObject(type, id, serializedAdditionalRawData); + return new UnknownRunStepDetailsToolCallsObjectToolCallsObject(id, kind, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +89,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - RunStepToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override RunStepToolCall 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepToolCall(document.RootElement, options); } default: @@ -129,16 +107,5 @@ RunStepToolCall IPersistableModel.Create(BinaryData data, Model } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepDetailsToolCallsObjectToolCallsObject FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepDetailsToolCallsObjectToolCallsObject(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.cs b/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.cs index 64ca9200a..64e0d13c9 100644 --- a/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.cs +++ b/src/Generated/Models/UnknownRunStepDetailsToolCallsObjectToolCallsObject.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepDetailsToolCallsObjectToolCallsObject : RunStepToolCall { - internal UnknownRunStepDetailsToolCallsObjectToolCallsObject(RunStepToolCallKind kind, string id, IDictionary serializedAdditionalRawData) : base(kind, id, serializedAdditionalRawData) - { - } - - internal UnknownRunStepDetailsToolCallsObjectToolCallsObject() + internal UnknownRunStepDetailsToolCallsObjectToolCallsObject(string id, Assistants.RunStepToolCallKind kind, IDictionary additionalBinaryDataProperties) : base(id, kind, additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UnknownRunStepObjectStepDetails.Serialization.cs b/src/Generated/Models/UnknownRunStepObjectStepDetails.Serialization.cs index 142bdc28b..9eed83689 100644 --- a/src/Generated/Models/UnknownRunStepObjectStepDetails.Serialization.cs +++ b/src/Generated/Models/UnknownRunStepObjectStepDetails.Serialization.cs @@ -3,95 +3,77 @@ #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Assistants { internal partial class UnknownRunStepObjectStepDetails : IJsonModel { + internal UnknownRunStepObjectStepDetails() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(RunStepDetails)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); + base.JsonModelWriteCore(writer, options); } - RunStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected override RunStepDetails JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(RunStepDetails)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeRunStepDetails(document.RootElement, options); } - internal static UnknownRunStepObjectStepDetails DeserializeUnknownRunStepObjectStepDetails(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownRunStepObjectStepDetails DeserializeUnknownRunStepObjectStepDetails(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + string @type = "unknown"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("type"u8)) + if (prop.NameEquals("type"u8)) { - type = property.Value.GetString(); + @type = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new UnknownRunStepObjectStepDetails(type, serializedAdditionalRawData); + return new UnknownRunStepObjectStepDetails(@type, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -101,15 +83,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opti } } - RunStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + RunStepDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected override RunStepDetails 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeRunStepDetails(document.RootElement, options); } default: @@ -118,16 +101,5 @@ RunStepDetails IPersistableModel.Create(BinaryData data, ModelRe } string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static new UnknownRunStepObjectStepDetails FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUnknownRunStepObjectStepDetails(document.RootElement); - } - - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } } } diff --git a/src/Generated/Models/UnknownRunStepObjectStepDetails.cs b/src/Generated/Models/UnknownRunStepObjectStepDetails.cs index e91259e4e..fa6a7a879 100644 --- a/src/Generated/Models/UnknownRunStepObjectStepDetails.cs +++ b/src/Generated/Models/UnknownRunStepObjectStepDetails.cs @@ -9,11 +9,7 @@ namespace OpenAI.Assistants { internal partial class UnknownRunStepObjectStepDetails : RunStepDetails { - internal UnknownRunStepObjectStepDetails(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - internal UnknownRunStepObjectStepDetails() + internal UnknownRunStepObjectStepDetails(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) { } } diff --git a/src/Generated/Models/UserChatMessage.Serialization.cs b/src/Generated/Models/UserChatMessage.Serialization.cs index 172dfb695..300edf218 100644 --- a/src/Generated/Models/UserChatMessage.Serialization.cs +++ b/src/Generated/Models/UserChatMessage.Serialization.cs @@ -7,68 +7,81 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.Chat { public partial class UserChatMessage : IJsonModel { - UserChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(UserChatMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(UserChatMessage)} does not support writing '{format}' format."); + } + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(ParticipantName) && _additionalBinaryDataProperties?.ContainsKey("name") != true) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(ParticipantName); } + } + + UserChatMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (UserChatMessage)JsonModelCreateCore(ref reader, options); + 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(UserChatMessage)} does not support reading '{format}' format."); + } using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeUserChatMessage(document.RootElement, options); } - internal static UserChatMessage DeserializeUserChatMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static UserChatMessage DeserializeUserChatMessage(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string name = default; - ChatMessageRole role = default; + Chat.ChatMessageRole role = default; ChatMessageContent content = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + string participantName = default; + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("role"u8)) { - name = property.Value.GetString(); + role = prop.Value.GetString().ToChatMessageRole(); continue; } - if (property.NameEquals("role"u8)) + if (prop.NameEquals("content"u8)) { - role = property.Value.GetString().ToChatMessageRole(); + DeserializeContentValue(prop, ref content); continue; } - if (property.NameEquals("content"u8)) + if (prop.NameEquals("name"u8)) { - DeserializeContentValue(property, ref content); + participantName = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; // CUSTOM: Initialize Content collection property. - return new UserChatMessage(role, content ?? new ChatMessageContent(), serializedAdditionalRawData, name); + return new UserChatMessage(role, content ?? new ChatMessageContent(), additionalBinaryDataProperties, participantName); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -78,15 +91,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions opt } } - UserChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + UserChatMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (UserChatMessage)PersistableModelCreateCore(data, options); + 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeUserChatMessage(document.RootElement, options); } default: @@ -96,15 +110,20 @@ UserChatMessage IPersistableModel.Create(BinaryData data, Model string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new UserChatMessage FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(UserChatMessage userChatMessage) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeUserChatMessage(document.RootElement); + if (userChatMessage == null) + { + return null; + } + return BinaryContent.Create(userChatMessage, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator UserChatMessage(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeUserChatMessage(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/UserChatMessage.cs b/src/Generated/Models/UserChatMessage.cs index 0f01a90ae..259270b7f 100644 --- a/src/Generated/Models/UserChatMessage.cs +++ b/src/Generated/Models/UserChatMessage.cs @@ -9,13 +9,9 @@ namespace OpenAI.Chat { public partial class UserChatMessage : ChatMessage { - internal UserChatMessage(ChatMessageRole role, ChatMessageContent content, IDictionary serializedAdditionalRawData, string participantName) : base(role, content, serializedAdditionalRawData) + internal UserChatMessage(Chat.ChatMessageRole role, ChatMessageContent content, IDictionary additionalBinaryDataProperties, string participantName) : base(role, content, additionalBinaryDataProperties) { ParticipantName = participantName; } - - internal UserChatMessage() - { - } } } diff --git a/src/Generated/Models/VectorStore.Serialization.cs b/src/Generated/Models/VectorStore.Serialization.cs index d2aacb781..8779c4de8 100644 --- a/src/Generated/Models/VectorStore.Serialization.cs +++ b/src/Generated/Models/VectorStore.Serialization.cs @@ -7,61 +7,61 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStore : IJsonModel { + internal VectorStore() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStore)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) { writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true) + if (_additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("usage_bytes") != true) + if (_additionalBinaryDataProperties?.ContainsKey("usage_bytes") != true) { writer.WritePropertyName("usage_bytes"u8); writer.WriteNumberValue(UsageBytes); } - if (SerializedAdditionalRawData?.ContainsKey("file_counts") != true) + if (_additionalBinaryDataProperties?.ContainsKey("file_counts") != true) { writer.WritePropertyName("file_counts"u8); writer.WriteObjectValue(FileCounts, options); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("expires_after") != true && Optional.IsDefined(ExpirationPolicy)) - { - writer.WritePropertyName("expires_after"u8); - writer.WriteObjectValue(ExpirationPolicy, options); - } - if (SerializedAdditionalRawData?.ContainsKey("expires_at") != true && Optional.IsDefined(ExpiresAt)) + if (Optional.IsDefined(ExpiresAt) && _additionalBinaryDataProperties?.ContainsKey("expires_at") != true) { if (ExpiresAt != null) { @@ -70,10 +70,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } else { - writer.WriteNull("expires_at"); + writer.WriteNull("expiresAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("last_active_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_active_at") != true) { if (LastActiveAt != null) { @@ -82,10 +82,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } else { - writer.WriteNull("last_active_at"); + writer.WriteNull("lastActiveAt"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true) + if (true && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { @@ -94,18 +94,33 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (Optional.IsDefined(ExpirationPolicy) && _additionalBinaryDataProperties?.ContainsKey("expires_after") != true) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpirationPolicy, options); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -113,7 +128,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -122,149 +137,152 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio #endif } } - writer.WriteEndObject(); } - VectorStore IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStore IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStore JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStore)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStore(document.RootElement, options); } - internal static VectorStore DeserializeVectorStore(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStore DeserializeVectorStore(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string id = default; - InternalVectorStoreObjectObject @object = default; DateTimeOffset createdAt = default; string name = default; int usageBytes = default; VectorStoreFileCounts fileCounts = default; - VectorStoreStatus status = default; - VectorStoreExpirationPolicy expiresAfter = default; + VectorStores.VectorStoreStatus status = default; DateTimeOffset? expiresAt = default; DateTimeOffset? lastActiveAt = default; IReadOnlyDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + InternalVectorStoreObjectObject @object = default; + VectorStoreExpirationPolicy expirationPolicy = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) - { - @object = new InternalVectorStoreObjectObject(property.Value.GetString()); - continue; - } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("id"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + id = prop.Value.GetString(); continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("created_at"u8)) { - name = property.Value.GetString(); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("usage_bytes"u8)) + if (prop.NameEquals("name"u8)) { - usageBytes = property.Value.GetInt32(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("file_counts"u8)) + if (prop.NameEquals("usage_bytes"u8)) { - fileCounts = VectorStoreFileCounts.DeserializeVectorStoreFileCounts(property.Value, options); + usageBytes = prop.Value.GetInt32(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("file_counts"u8)) { - status = property.Value.GetString().ToVectorStoreStatus(); + fileCounts = VectorStoreFileCounts.DeserializeVectorStoreFileCounts(prop.Value, options); continue; } - if (property.NameEquals("expires_after"u8)) + if (prop.NameEquals("status"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + status = prop.Value.GetString().ToVectorStoreStatus(); continue; } - if (property.NameEquals("expires_at"u8)) + if (prop.NameEquals("expires_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { expiresAt = null; continue; } - expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("last_active_at"u8)) + if (prop.NameEquals("last_active_at"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { lastActiveAt = null; continue; } - lastActiveAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + lastActiveAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { metadata = new ChangeTrackingDictionary(); continue; } Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + foreach (var prop0 in prop.Value.EnumerateObject()) { - dictionary.Add(property0.Name, property0.Value.GetString()); + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } } metadata = dictionary; continue; } + if (prop.NameEquals("object"u8)) + { + @object = new InternalVectorStoreObjectObject(prop.Value.GetString()); + continue; + } + if (prop.NameEquals("expires_after"u8)) + { + if (prop.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expirationPolicy = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(prop.Value, options); + continue; + } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new VectorStore( id, - @object, createdAt, name, usageBytes, fileCounts, status, - expiresAfter, expiresAt, lastActiveAt, metadata, - serializedAdditionalRawData); + @object, + expirationPolicy, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -274,15 +292,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptions options } } - VectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStore 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStore(document.RootElement, options); } default: @@ -292,15 +311,20 @@ VectorStore IPersistableModel.Create(BinaryData data, ModelReaderWr string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStore FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStore vectorStore) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStore(document.RootElement); + if (vectorStore == null) + { + return null; + } + return BinaryContent.Create(vectorStore, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStore(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStore(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStore.cs b/src/Generated/Models/VectorStore.cs index 3f39a41e2..b86c907e8 100644 --- a/src/Generated/Models/VectorStore.cs +++ b/src/Generated/Models/VectorStore.cs @@ -4,18 +4,16 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStore { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal VectorStore(string id, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCounts fileCounts, VectorStoreStatus status, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + private protected IDictionary _additionalBinaryDataProperties; + internal VectorStore(string id, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCounts fileCounts, VectorStores.VectorStoreStatus status, DateTimeOffset? lastActiveAt) + { Id = id; CreatedAt = createdAt; Name = name; @@ -23,38 +21,47 @@ internal VectorStore(string id, DateTimeOffset createdAt, string name, int usage FileCounts = fileCounts; Status = status; LastActiveAt = lastActiveAt; - Metadata = metadata; + Metadata = new ChangeTrackingDictionary(); } - internal VectorStore(string id, InternalVectorStoreObjectObject @object, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCounts fileCounts, VectorStoreStatus status, VectorStoreExpirationPolicy expirationPolicy, DateTimeOffset? expiresAt, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStore(string id, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCounts fileCounts, VectorStores.VectorStoreStatus status, DateTimeOffset? expiresAt, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata, InternalVectorStoreObjectObject @object, VectorStoreExpirationPolicy expirationPolicy, IDictionary additionalBinaryDataProperties) { Id = id; - Object = @object; CreatedAt = createdAt; Name = name; UsageBytes = usageBytes; FileCounts = fileCounts; Status = status; - ExpirationPolicy = expirationPolicy; ExpiresAt = expiresAt; LastActiveAt = lastActiveAt; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal VectorStore() - { + this.Object = @object; + ExpirationPolicy = expirationPolicy; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Id { get; } public DateTimeOffset CreatedAt { get; } + public string Name { get; } + public int UsageBytes { get; } + public VectorStoreFileCounts FileCounts { get; } - public VectorStoreStatus Status { get; } + + public VectorStores.VectorStoreStatus Status { get; } + public DateTimeOffset? ExpiresAt { get; } + public DateTimeOffset? LastActiveAt { get; } + public IReadOnlyDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreBatchFileJob.Serialization.cs b/src/Generated/Models/VectorStoreBatchFileJob.Serialization.cs index bdfa594c4..643b8ac93 100644 --- a/src/Generated/Models/VectorStoreBatchFileJob.Serialization.cs +++ b/src/Generated/Models/VectorStoreBatchFileJob.Serialization.cs @@ -7,53 +7,63 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreBatchFileJob : IJsonModel { + internal VectorStoreBatchFileJob() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreBatchFileJob)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(BatchId); - } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteObjectValue(Object, options); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("vector_store_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("vector_store_id") != true) { writer.WritePropertyName("vector_store_id"u8); writer.WriteStringValue(VectorStoreId); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("file_counts") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(BatchId); + } + if (_additionalBinaryDataProperties?.ContainsKey("file_counts") != true) { writer.WritePropertyName("file_counts"u8); writer.WriteObjectValue(FileCounts, options); } - if (SerializedAdditionalRawData != null) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("object"u8); + writer.WriteObjectValue(this.Object, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -61,7 +71,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -70,90 +80,86 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade #endif } } - writer.WriteEndObject(); } - VectorStoreBatchFileJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreBatchFileJob IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreBatchFileJob JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreBatchFileJob)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreBatchFileJob(document.RootElement, options); } - internal static VectorStoreBatchFileJob DeserializeVectorStoreBatchFileJob(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreBatchFileJob DeserializeVectorStoreBatchFileJob(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; - object @object = default; DateTimeOffset createdAt = default; string vectorStoreId = default; VectorStoreBatchFileJobStatus status = default; + string batchId = default; VectorStoreFileCounts fileCounts = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + object @object = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("created_at"u8)) { - id = property.Value.GetString(); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("vector_store_id"u8)) { - @object = property.Value.GetObject(); + vectorStoreId = prop.Value.GetString(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("status"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + status = new VectorStoreBatchFileJobStatus(prop.Value.GetString()); continue; } - if (property.NameEquals("vector_store_id"u8)) + if (prop.NameEquals("id"u8)) { - vectorStoreId = property.Value.GetString(); + batchId = prop.Value.GetString(); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("file_counts"u8)) { - status = new VectorStoreBatchFileJobStatus(property.Value.GetString()); + fileCounts = VectorStoreFileCounts.DeserializeVectorStoreFileCounts(prop.Value, options); continue; } - if (property.NameEquals("file_counts"u8)) + if (prop.NameEquals("object"u8)) { - fileCounts = VectorStoreFileCounts.DeserializeVectorStoreFileCounts(property.Value, options); + @object = prop.Value.GetObject(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new VectorStoreBatchFileJob( - id, - @object, createdAt, vectorStoreId, status, + batchId, fileCounts, - serializedAdditionalRawData); + @object, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -163,15 +169,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOpt } } - VectorStoreBatchFileJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreBatchFileJob IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreBatchFileJob 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreBatchFileJob(document.RootElement, options); } default: @@ -181,15 +188,20 @@ VectorStoreBatchFileJob IPersistableModel.Create(Binary string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreBatchFileJob FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreBatchFileJob vectorStoreBatchFileJob) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreBatchFileJob(document.RootElement); + if (vectorStoreBatchFileJob == null) + { + return null; + } + return BinaryContent.Create(vectorStoreBatchFileJob, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreBatchFileJob(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreBatchFileJob(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreBatchFileJob.cs b/src/Generated/Models/VectorStoreBatchFileJob.cs index a584a5e60..919b553ca 100644 --- a/src/Generated/Models/VectorStoreBatchFileJob.cs +++ b/src/Generated/Models/VectorStoreBatchFileJob.cs @@ -9,37 +9,38 @@ namespace OpenAI.VectorStores { public partial class VectorStoreBatchFileJob { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal VectorStoreBatchFileJob(string batchId, DateTimeOffset createdAt, string vectorStoreId, VectorStoreBatchFileJobStatus status, VectorStoreFileCounts fileCounts) - { - Argument.AssertNotNull(batchId, nameof(batchId)); - Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); - Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + private protected IDictionary _additionalBinaryDataProperties; - BatchId = batchId; + internal VectorStoreBatchFileJob(DateTimeOffset createdAt, string vectorStoreId, VectorStoreBatchFileJobStatus status, string batchId, VectorStoreFileCounts fileCounts) + { CreatedAt = createdAt; VectorStoreId = vectorStoreId; Status = status; + BatchId = batchId; FileCounts = fileCounts; } - internal VectorStoreBatchFileJob(string batchId, object @object, DateTimeOffset createdAt, string vectorStoreId, VectorStoreBatchFileJobStatus status, VectorStoreFileCounts fileCounts, IDictionary serializedAdditionalRawData) + internal VectorStoreBatchFileJob(DateTimeOffset createdAt, string vectorStoreId, VectorStoreBatchFileJobStatus status, string batchId, VectorStoreFileCounts fileCounts, object @object, IDictionary additionalBinaryDataProperties) { - BatchId = batchId; - Object = @object; CreatedAt = createdAt; VectorStoreId = vectorStoreId; Status = status; + BatchId = batchId; FileCounts = fileCounts; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal VectorStoreBatchFileJob() - { + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public DateTimeOffset CreatedAt { get; } + public string VectorStoreId { get; } + public VectorStoreBatchFileJobStatus Status { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreBatchFileJobStatus.cs b/src/Generated/Models/VectorStoreBatchFileJobStatus.cs index c47559446..6a9907c96 100644 --- a/src/Generated/Models/VectorStoreBatchFileJobStatus.cs +++ b/src/Generated/Models/VectorStoreBatchFileJobStatus.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { public readonly partial struct VectorStoreBatchFileJobStatus : IEquatable { private readonly string _value; - - public VectorStoreBatchFileJobStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string InProgressValue = "in_progress"; private const string CompletedValue = "completed"; private const string CancelledValue = "cancelled"; private const string FailedValue = "failed"; + public VectorStoreBatchFileJobStatus(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static VectorStoreBatchFileJobStatus InProgress { get; } = new VectorStoreBatchFileJobStatus(InProgressValue); + public static VectorStoreBatchFileJobStatus Completed { get; } = new VectorStoreBatchFileJobStatus(CompletedValue); + public static VectorStoreBatchFileJobStatus Cancelled { get; } = new VectorStoreBatchFileJobStatus(CancelledValue); + public static VectorStoreBatchFileJobStatus Failed { get; } = new VectorStoreBatchFileJobStatus(FailedValue); + public static bool operator ==(VectorStoreBatchFileJobStatus left, VectorStoreBatchFileJobStatus right) => left.Equals(right); + public static bool operator !=(VectorStoreBatchFileJobStatus left, VectorStoreBatchFileJobStatus right) => !left.Equals(right); + public static implicit operator VectorStoreBatchFileJobStatus(string value) => new VectorStoreBatchFileJobStatus(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is VectorStoreBatchFileJobStatus other && Equals(other); + public bool Equals(VectorStoreBatchFileJobStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/VectorStoreCollectionOrder.cs b/src/Generated/Models/VectorStoreCollectionOrder.cs index d8e019322..02d58180c 100644 --- a/src/Generated/Models/VectorStoreCollectionOrder.cs +++ b/src/Generated/Models/VectorStoreCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { public readonly partial struct VectorStoreCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public VectorStoreCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(VectorStoreCollectionOrder left, VectorStoreCollectionOrder right) => left.Equals(right); + public static bool operator !=(VectorStoreCollectionOrder left, VectorStoreCollectionOrder right) => !left.Equals(right); + public static implicit operator VectorStoreCollectionOrder(string value) => new VectorStoreCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is VectorStoreCollectionOrder other && Equals(other); + public bool Equals(VectorStoreCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs b/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs index 3004632e0..68824cf3c 100644 --- a/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs +++ b/src/Generated/Models/VectorStoreCreationHelper.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; using OpenAI.VectorStores; namespace OpenAI.Assistants @@ -15,42 +16,57 @@ public partial class VectorStoreCreationHelper : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreCreationHelper)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) - { - writer.WritePropertyName("chunking_strategy"u8); - writer.WriteObjectValue(ChunkingStrategy, options); - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { writer.WritePropertyName("metadata"u8); writer.WriteStartObject(); foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(ChunkingStrategy) && _additionalBinaryDataProperties?.ContainsKey("chunking_strategy") != true) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -58,7 +74,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -67,87 +83,97 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - VectorStoreCreationHelper IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreCreationHelper IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreCreationHelper JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreCreationHelper)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreCreationHelper(document.RootElement, options); } - internal static VectorStoreCreationHelper DeserializeVectorStoreCreationHelper(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreCreationHelper DeserializeVectorStoreCreationHelper(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; - FileChunkingStrategy chunkingStrategy = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + FileChunkingStrategy chunkingStrategy = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } - if (property.NameEquals("chunking_strategy"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(property.Value, options); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("chunking_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreCreationHelper(fileIds ?? new ChangeTrackingList(), chunkingStrategy, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new VectorStoreCreationHelper(fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), chunkingStrategy, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -157,15 +183,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - VectorStoreCreationHelper IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreCreationHelper IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreCreationHelper 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreCreationHelper(document.RootElement, options); } default: @@ -175,15 +202,20 @@ VectorStoreCreationHelper IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreCreationHelper FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreCreationHelper vectorStoreCreationHelper) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreCreationHelper(document.RootElement); + if (vectorStoreCreationHelper == null) + { + return null; + } + return BinaryContent.Create(vectorStoreCreationHelper, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreCreationHelper(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreCreationHelper(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreCreationHelper.cs b/src/Generated/Models/VectorStoreCreationHelper.cs index 6871ab916..935039ea4 100644 --- a/src/Generated/Models/VectorStoreCreationHelper.cs +++ b/src/Generated/Models/VectorStoreCreationHelper.cs @@ -4,28 +4,37 @@ using System; using System.Collections.Generic; +using OpenAI; using OpenAI.VectorStores; namespace OpenAI.Assistants { public partial class VectorStoreCreationHelper { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public VectorStoreCreationHelper() { FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - internal VectorStoreCreationHelper(IList fileIds, FileChunkingStrategy chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreCreationHelper(IList fileIds, IDictionary metadata, FileChunkingStrategy chunkingStrategy, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; - ChunkingStrategy = chunkingStrategy; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + ChunkingStrategy = chunkingStrategy; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + public IDictionary Metadata { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreCreationOptions.Serialization.cs b/src/Generated/Models/VectorStoreCreationOptions.Serialization.cs index 4b08b506a..91403959b 100644 --- a/src/Generated/Models/VectorStoreCreationOptions.Serialization.cs +++ b/src/Generated/Models/VectorStoreCreationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,39 +15,39 @@ public partial class VectorStoreCreationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreCreationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("file_ids") != true && Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(FileIds) && _additionalBinaryDataProperties?.ContainsKey("file_ids") != true) { writer.WritePropertyName("file_ids"u8); writer.WriteStartArray(); - foreach (var item in FileIds) + foreach (string item in FileIds) { + if (item == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { writer.WritePropertyName("name"u8); writer.WriteStringValue(Name); } - if (SerializedAdditionalRawData?.ContainsKey("expires_after") != true && Optional.IsDefined(ExpirationPolicy)) - { - writer.WritePropertyName("expires_after"u8); - writer.WriteObjectValue(ExpirationPolicy, options); - } - if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) - { - writer.WritePropertyName("chunking_strategy"u8); - writer.WriteObjectValue(ChunkingStrategy, options); - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -55,18 +56,33 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); } } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(ExpirationPolicy) && _additionalBinaryDataProperties?.ContainsKey("expires_after") != true) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpirationPolicy, options); + } + if (Optional.IsDefined(ChunkingStrategy) && _additionalBinaryDataProperties?.ContainsKey("chunking_strategy") != true) { - foreach (var item in SerializedAdditionalRawData) + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (true && _additionalBinaryDataProperties != null) + { + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -74,7 +90,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -83,109 +99,119 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - VectorStoreCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreCreationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreCreationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreCreationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreCreationOptions(document.RootElement, options); } - internal static VectorStoreCreationOptions DeserializeVectorStoreCreationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreCreationOptions DeserializeVectorStoreCreationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } IList fileIds = default; string name = default; - VectorStoreExpirationPolicy expiresAfter = default; - FileChunkingStrategy chunkingStrategy = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + VectorStoreExpirationPolicy expirationPolicy = default; + FileChunkingStrategy chunkingStrategy = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("file_ids"u8)) + if (prop.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + foreach (var item in prop.Value.EnumerateArray()) { - array.Add(item.GetString()); + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetString()); + } } fileIds = array; continue; } - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("expires_after"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("chunking_strategy"u8)) + if (prop.NameEquals("expires_after"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(property.Value, options); + expirationPolicy = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(prop.Value, options); continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("chunking_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new VectorStoreCreationOptions( fileIds ?? new ChangeTrackingList(), name, - expiresAfter, - chunkingStrategy, metadata ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); + expirationPolicy, + chunkingStrategy, + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -195,15 +221,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - VectorStoreCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreCreationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreCreationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreCreationOptions(document.RootElement, options); } default: @@ -213,15 +240,20 @@ VectorStoreCreationOptions IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreCreationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreCreationOptions vectorStoreCreationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreCreationOptions(document.RootElement); + if (vectorStoreCreationOptions == null) + { + return null; + } + return BinaryContent.Create(vectorStoreCreationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreCreationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreCreationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreCreationOptions.cs b/src/Generated/Models/VectorStoreCreationOptions.cs index 6d5f31216..563e1c7d3 100644 --- a/src/Generated/Models/VectorStoreCreationOptions.cs +++ b/src/Generated/Models/VectorStoreCreationOptions.cs @@ -4,30 +4,40 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreCreationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public VectorStoreCreationOptions() { FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - internal VectorStoreCreationOptions(IList fileIds, string name, VectorStoreExpirationPolicy expirationPolicy, FileChunkingStrategy chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreCreationOptions(IList fileIds, string name, IDictionary metadata, VectorStoreExpirationPolicy expirationPolicy, FileChunkingStrategy chunkingStrategy, IDictionary additionalBinaryDataProperties) { FileIds = fileIds; Name = name; + Metadata = metadata; ExpirationPolicy = expirationPolicy; ChunkingStrategy = chunkingStrategy; - Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public IList FileIds { get; } + public string Name { get; set; } + public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreDeletionResult.Serialization.cs b/src/Generated/Models/VectorStoreDeletionResult.Serialization.cs index 2504be9db..ffbcc14f0 100644 --- a/src/Generated/Models/VectorStoreDeletionResult.Serialization.cs +++ b/src/Generated/Models/VectorStoreDeletionResult.Serialization.cs @@ -7,38 +7,48 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreDeletionResult : IJsonModel { + internal VectorStoreDeletionResult() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreDeletionResult)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(VectorStoreId); - } - if (SerializedAdditionalRawData?.ContainsKey("deleted") != true) + if (_additionalBinaryDataProperties?.ContainsKey("deleted") != true) { writer.WritePropertyName("deleted"u8); writer.WriteBooleanValue(Deleted); } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(VectorStoreId); + } + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) { writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); + writer.WriteStringValue(this.Object.ToString()); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -46,7 +56,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -55,65 +65,61 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea #endif } } - writer.WriteEndObject(); } - VectorStoreDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreDeletionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreDeletionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreDeletionResult)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreDeletionResult(document.RootElement, options); } - internal static VectorStoreDeletionResult DeserializeVectorStoreDeletionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreDeletionResult DeserializeVectorStoreDeletionResult(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; bool deleted = default; + string vectorStoreId = default; InternalDeleteVectorStoreResponseObject @object = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("deleted"u8)) { - id = property.Value.GetString(); + deleted = prop.Value.GetBoolean(); continue; } - if (property.NameEquals("deleted"u8)) + if (prop.NameEquals("id"u8)) { - deleted = property.Value.GetBoolean(); + vectorStoreId = prop.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("object"u8)) { - @object = new InternalDeleteVectorStoreResponseObject(property.Value.GetString()); + @object = new InternalDeleteVectorStoreResponseObject(prop.Value.GetString()); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreDeletionResult(id, deleted, @object, serializedAdditionalRawData); + return new VectorStoreDeletionResult(deleted, vectorStoreId, @object, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -123,15 +129,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterO } } - VectorStoreDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreDeletionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreDeletionResult 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreDeletionResult(document.RootElement, options); } default: @@ -141,15 +148,20 @@ VectorStoreDeletionResult IPersistableModel.Create(Bi string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreDeletionResult FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreDeletionResult vectorStoreDeletionResult) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreDeletionResult(document.RootElement); + if (vectorStoreDeletionResult == null) + { + return null; + } + return BinaryContent.Create(vectorStoreDeletionResult, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreDeletionResult(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreDeletionResult(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreDeletionResult.cs b/src/Generated/Models/VectorStoreDeletionResult.cs index 1e046bda0..35a6a2908 100644 --- a/src/Generated/Models/VectorStoreDeletionResult.cs +++ b/src/Generated/Models/VectorStoreDeletionResult.cs @@ -9,26 +9,28 @@ namespace OpenAI.VectorStores { public partial class VectorStoreDeletionResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal VectorStoreDeletionResult(string vectorStoreId, bool deleted) - { - Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + private protected IDictionary _additionalBinaryDataProperties; - VectorStoreId = vectorStoreId; + internal VectorStoreDeletionResult(bool deleted, string vectorStoreId) + { Deleted = deleted; + VectorStoreId = vectorStoreId; } - internal VectorStoreDeletionResult(string vectorStoreId, bool deleted, InternalDeleteVectorStoreResponseObject @object, IDictionary serializedAdditionalRawData) + internal VectorStoreDeletionResult(bool deleted, string vectorStoreId, InternalDeleteVectorStoreResponseObject @object, IDictionary additionalBinaryDataProperties) { - VectorStoreId = vectorStoreId; Deleted = deleted; - Object = @object; - SerializedAdditionalRawData = serializedAdditionalRawData; + VectorStoreId = vectorStoreId; + this.Object = @object; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal VectorStoreDeletionResult() + public bool Deleted { get; } + + internal IDictionary SerializedAdditionalRawData { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; } - public bool Deleted { get; } } } diff --git a/src/Generated/Models/VectorStoreExpirationAnchor.Serialization.cs b/src/Generated/Models/VectorStoreExpirationAnchor.Serialization.cs index 90af403e1..0c7b2962c 100644 --- a/src/Generated/Models/VectorStoreExpirationAnchor.Serialization.cs +++ b/src/Generated/Models/VectorStoreExpirationAnchor.Serialization.cs @@ -8,15 +8,18 @@ namespace OpenAI.VectorStores { internal static partial class VectorStoreExpirationAnchorExtensions { - public static string ToSerialString(this VectorStoreExpirationAnchor value) => value switch + public static string ToSerialString(this VectorStores.VectorStoreExpirationAnchor value) => value switch { - VectorStoreExpirationAnchor.LastActiveAt => "last_active_at", + VectorStores.VectorStoreExpirationAnchor.LastActiveAt => "last_active_at", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreExpirationAnchor value.") }; - public static VectorStoreExpirationAnchor ToVectorStoreExpirationAnchor(this string value) + public static VectorStores.VectorStoreExpirationAnchor ToVectorStoreExpirationAnchor(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "last_active_at")) return VectorStoreExpirationAnchor.LastActiveAt; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "last_active_at")) + { + return VectorStores.VectorStoreExpirationAnchor.LastActiveAt; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreExpirationAnchor value."); } } diff --git a/src/Generated/Models/VectorStoreExpirationPolicy.Serialization.cs b/src/Generated/Models/VectorStoreExpirationPolicy.Serialization.cs index 76b1d5d3c..a6e7d9c89 100644 --- a/src/Generated/Models/VectorStoreExpirationPolicy.Serialization.cs +++ b/src/Generated/Models/VectorStoreExpirationPolicy.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,26 +15,31 @@ public partial class VectorStoreExpirationPolicy : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreExpirationPolicy)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("anchor") != true) + if (_additionalBinaryDataProperties?.ContainsKey("anchor") != true) { writer.WritePropertyName("anchor"u8); writer.WriteStringValue(_anchor.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("days") != true) + if (_additionalBinaryDataProperties?.ContainsKey("days") != true) { writer.WritePropertyName("days"u8); writer.WriteNumberValue(_days); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +47,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +56,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR #endif } } - writer.WriteEndObject(); } - VectorStoreExpirationPolicy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreExpirationPolicy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreExpirationPolicy JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreExpirationPolicy(document.RootElement, options); } - internal static VectorStoreExpirationPolicy DeserializeVectorStoreExpirationPolicy(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreExpirationPolicy DeserializeVectorStoreExpirationPolicy(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - VectorStoreExpirationAnchor anchor = default; + VectorStores.VectorStoreExpirationAnchor anchor = default; int days = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("anchor"u8)) + if (prop.NameEquals("anchor"u8)) { - anchor = property.Value.GetString().ToVectorStoreExpirationAnchor(); + anchor = prop.Value.GetString().ToVectorStoreExpirationAnchor(); continue; } - if (property.NameEquals("days"u8)) + if (prop.NameEquals("days"u8)) { - days = property.Value.GetInt32(); + days = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreExpirationPolicy(anchor, days, serializedAdditionalRawData); + return new VectorStoreExpirationPolicy(anchor, days, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +114,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - VectorStoreExpirationPolicy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreExpirationPolicy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreExpirationPolicy 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreExpirationPolicy(document.RootElement, options); } default: @@ -130,15 +133,20 @@ VectorStoreExpirationPolicy IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreExpirationPolicy FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreExpirationPolicy vectorStoreExpirationPolicy) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreExpirationPolicy(document.RootElement); + if (vectorStoreExpirationPolicy == null) + { + return null; + } + return BinaryContent.Create(vectorStoreExpirationPolicy, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreExpirationPolicy(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreExpirationPolicy(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreExpirationPolicy.cs b/src/Generated/Models/VectorStoreExpirationPolicy.cs index 3fd71c7e7..2a6147ceb 100644 --- a/src/Generated/Models/VectorStoreExpirationPolicy.cs +++ b/src/Generated/Models/VectorStoreExpirationPolicy.cs @@ -9,5 +9,12 @@ namespace OpenAI.VectorStores { public partial class VectorStoreExpirationPolicy { + private protected IDictionary _additionalBinaryDataProperties; + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreFileAssociation.Serialization.cs b/src/Generated/Models/VectorStoreFileAssociation.Serialization.cs index ede8e0d5b..38cb0416e 100644 --- a/src/Generated/Models/VectorStoreFileAssociation.Serialization.cs +++ b/src/Generated/Models/VectorStoreFileAssociation.Serialization.cs @@ -7,51 +7,46 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreFileAssociation : IJsonModel { + internal VectorStoreFileAssociation() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreFileAssociation)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(FileId); - } - if (SerializedAdditionalRawData?.ContainsKey("object") != true) - { - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("usage_bytes") != true) - { - writer.WritePropertyName("usage_bytes"u8); - writer.WriteNumberValue(Size); - } - if (SerializedAdditionalRawData?.ContainsKey("created_at") != true) + if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true) { writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); } - if (SerializedAdditionalRawData?.ContainsKey("vector_store_id") != true) + if (_additionalBinaryDataProperties?.ContainsKey("vector_store_id") != true) { writer.WritePropertyName("vector_store_id"u8); writer.WriteStringValue(VectorStoreId); } - if (SerializedAdditionalRawData?.ContainsKey("status") != true) + if (_additionalBinaryDataProperties?.ContainsKey("status") != true) { writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToSerialString()); } - if (SerializedAdditionalRawData?.ContainsKey("last_error") != true) + if (_additionalBinaryDataProperties?.ContainsKey("last_error") != true) { if (LastError != null) { @@ -60,17 +55,32 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } else { - writer.WriteNull("last_error"); + writer.WriteNull("lastError"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("chunking_strategy") != true && Optional.IsDefined(ChunkingStrategy)) + if (_additionalBinaryDataProperties?.ContainsKey("object") != true) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(this.Object.ToString()); + } + if (_additionalBinaryDataProperties?.ContainsKey("id") != true) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(FileId); + } + if (_additionalBinaryDataProperties?.ContainsKey("usage_bytes") != true) + { + writer.WritePropertyName("usage_bytes"u8); + writer.WriteNumberValue(Size); + } + if (Optional.IsDefined(ChunkingStrategy) && _additionalBinaryDataProperties?.ContainsKey("chunking_strategy") != true) { writer.WritePropertyName("chunking_strategy"u8); writer.WriteObjectValue(ChunkingStrategy, options); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -78,7 +88,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -87,113 +97,109 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe #endif } } - writer.WriteEndObject(); } - VectorStoreFileAssociation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreFileAssociation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreFileAssociation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreFileAssociation)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreFileAssociation(document.RootElement, options); } - internal static VectorStoreFileAssociation DeserializeVectorStoreFileAssociation(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreFileAssociation DeserializeVectorStoreFileAssociation(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } - string id = default; - InternalVectorStoreFileObjectObject @object = default; - int usageBytes = default; DateTimeOffset createdAt = default; string vectorStoreId = default; - VectorStoreFileAssociationStatus status = default; + VectorStores.VectorStoreFileAssociationStatus status = default; VectorStoreFileAssociationError lastError = default; + InternalVectorStoreFileObjectObject @object = default; + string fileId = default; + int size = default; FileChunkingStrategy chunkingStrategy = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (prop.NameEquals("created_at"u8)) { - id = property.Value.GetString(); + createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64()); continue; } - if (property.NameEquals("object"u8)) + if (prop.NameEquals("vector_store_id"u8)) { - @object = new InternalVectorStoreFileObjectObject(property.Value.GetString()); + vectorStoreId = prop.Value.GetString(); continue; } - if (property.NameEquals("usage_bytes"u8)) + if (prop.NameEquals("status"u8)) { - usageBytes = property.Value.GetInt32(); + status = prop.Value.GetString().ToVectorStoreFileAssociationStatus(); continue; } - if (property.NameEquals("created_at"u8)) + if (prop.NameEquals("last_error"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + if (prop.Value.ValueKind == JsonValueKind.Null) + { + lastError = null; + continue; + } + lastError = VectorStoreFileAssociationError.DeserializeVectorStoreFileAssociationError(prop.Value, options); continue; } - if (property.NameEquals("vector_store_id"u8)) + if (prop.NameEquals("object"u8)) { - vectorStoreId = property.Value.GetString(); + @object = new InternalVectorStoreFileObjectObject(prop.Value.GetString()); continue; } - if (property.NameEquals("status"u8)) + if (prop.NameEquals("id"u8)) { - status = property.Value.GetString().ToVectorStoreFileAssociationStatus(); + fileId = prop.Value.GetString(); continue; } - if (property.NameEquals("last_error"u8)) + if (prop.NameEquals("usage_bytes"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - lastError = null; - continue; - } - lastError = VectorStoreFileAssociationError.DeserializeVectorStoreFileAssociationError(property.Value, options); + size = prop.Value.GetInt32(); continue; } - if (property.NameEquals("chunking_strategy"u8)) + if (prop.NameEquals("chunking_strategy"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { continue; } - chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(property.Value, options); + chunkingStrategy = FileChunkingStrategy.DeserializeFileChunkingStrategy(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new VectorStoreFileAssociation( - id, - @object, - usageBytes, createdAt, vectorStoreId, status, lastError, + @object, + fileId, + size, chunkingStrategy, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -203,15 +209,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriter } } - VectorStoreFileAssociation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreFileAssociation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreFileAssociation 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreFileAssociation(document.RootElement, options); } default: @@ -221,15 +228,20 @@ VectorStoreFileAssociation IPersistableModel.Create( string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreFileAssociation FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreFileAssociation vectorStoreFileAssociation) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreFileAssociation(document.RootElement); + if (vectorStoreFileAssociation == null) + { + return null; + } + return BinaryContent.Create(vectorStoreFileAssociation, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreFileAssociation(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileAssociation(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreFileAssociation.cs b/src/Generated/Models/VectorStoreFileAssociation.cs index c7da0b027..037763511 100644 --- a/src/Generated/Models/VectorStoreFileAssociation.cs +++ b/src/Generated/Models/VectorStoreFileAssociation.cs @@ -9,39 +9,43 @@ namespace OpenAI.VectorStores { public partial class VectorStoreFileAssociation { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal VectorStoreFileAssociation(string fileId, int size, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileAssociationStatus status, VectorStoreFileAssociationError lastError) - { - Argument.AssertNotNull(fileId, nameof(fileId)); - Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + private protected IDictionary _additionalBinaryDataProperties; - FileId = fileId; - Size = size; + internal VectorStoreFileAssociation(DateTimeOffset createdAt, string vectorStoreId, VectorStores.VectorStoreFileAssociationStatus status, VectorStoreFileAssociationError lastError, string fileId, int size) + { CreatedAt = createdAt; VectorStoreId = vectorStoreId; Status = status; LastError = lastError; + FileId = fileId; + Size = size; } - internal VectorStoreFileAssociation(string fileId, InternalVectorStoreFileObjectObject @object, int size, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileAssociationStatus status, VectorStoreFileAssociationError lastError, FileChunkingStrategy chunkingStrategy, IDictionary serializedAdditionalRawData) + internal VectorStoreFileAssociation(DateTimeOffset createdAt, string vectorStoreId, VectorStores.VectorStoreFileAssociationStatus status, VectorStoreFileAssociationError lastError, InternalVectorStoreFileObjectObject @object, string fileId, int size, FileChunkingStrategy chunkingStrategy, IDictionary additionalBinaryDataProperties) { - FileId = fileId; - Object = @object; - Size = size; CreatedAt = createdAt; VectorStoreId = vectorStoreId; Status = status; LastError = lastError; + this.Object = @object; + FileId = fileId; + Size = size; ChunkingStrategy = chunkingStrategy; - SerializedAdditionalRawData = serializedAdditionalRawData; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } - internal VectorStoreFileAssociation() - { - } public DateTimeOffset CreatedAt { get; } + public string VectorStoreId { get; } - public VectorStoreFileAssociationStatus Status { get; } + + public VectorStores.VectorStoreFileAssociationStatus Status { get; } + public VectorStoreFileAssociationError LastError { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreFileAssociationCollectionOrder.cs b/src/Generated/Models/VectorStoreFileAssociationCollectionOrder.cs index 02656b21d..0f1f67686 100644 --- a/src/Generated/Models/VectorStoreFileAssociationCollectionOrder.cs +++ b/src/Generated/Models/VectorStoreFileAssociationCollectionOrder.cs @@ -4,30 +4,37 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { public readonly partial struct VectorStoreFileAssociationCollectionOrder : IEquatable { private readonly string _value; + private const string AscValue = "asc"; + private const string DescValue = "desc"; public VectorStoreFileAssociationCollectionOrder(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); + Argument.AssertNotNull(value, nameof(value)); + + _value = value; } - private const string AscendingValue = "asc"; - private const string DescendingValue = "desc"; public static bool operator ==(VectorStoreFileAssociationCollectionOrder left, VectorStoreFileAssociationCollectionOrder right) => left.Equals(right); + public static bool operator !=(VectorStoreFileAssociationCollectionOrder left, VectorStoreFileAssociationCollectionOrder right) => !left.Equals(right); + public static implicit operator VectorStoreFileAssociationCollectionOrder(string value) => new VectorStoreFileAssociationCollectionOrder(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is VectorStoreFileAssociationCollectionOrder other && Equals(other); + public bool Equals(VectorStoreFileAssociationCollectionOrder other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/VectorStoreFileAssociationError.Serialization.cs b/src/Generated/Models/VectorStoreFileAssociationError.Serialization.cs index 9bc7e2126..d6e4ca8d5 100644 --- a/src/Generated/Models/VectorStoreFileAssociationError.Serialization.cs +++ b/src/Generated/Models/VectorStoreFileAssociationError.Serialization.cs @@ -7,33 +7,43 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreFileAssociationError : IJsonModel { + internal VectorStoreFileAssociationError() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreFileAssociationError)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) + if (_additionalBinaryDataProperties?.ContainsKey("code") != true) { writer.WritePropertyName("code"u8); writer.WriteStringValue(Code.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) + if (_additionalBinaryDataProperties?.ContainsKey("message") != true) { writer.WritePropertyName("message"u8); writer.WriteStringValue(Message); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -41,7 +51,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -50,59 +60,55 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo #endif } } - writer.WriteEndObject(); } - VectorStoreFileAssociationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreFileAssociationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreFileAssociationError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreFileAssociationError)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreFileAssociationError(document.RootElement, options); } - internal static VectorStoreFileAssociationError DeserializeVectorStoreFileAssociationError(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreFileAssociationError DeserializeVectorStoreFileAssociationError(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } VectorStoreFileAssociationErrorCode code = default; string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("code"u8)) + if (prop.NameEquals("code"u8)) { - code = new VectorStoreFileAssociationErrorCode(property.Value.GetString()); + code = new VectorStoreFileAssociationErrorCode(prop.Value.GetString()); continue; } - if (property.NameEquals("message"u8)) + if (prop.NameEquals("message"u8)) { - message = property.Value.GetString(); + message = prop.Value.GetString(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreFileAssociationError(code, message, serializedAdditionalRawData); + return new VectorStoreFileAssociationError(code, message, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +118,16 @@ BinaryData IPersistableModel.Write(ModelReaderW } } - VectorStoreFileAssociationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreFileAssociationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreFileAssociationError 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreFileAssociationError(document.RootElement, options); } default: @@ -130,15 +137,20 @@ VectorStoreFileAssociationError IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreFileAssociationError FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreFileAssociationError vectorStoreFileAssociationError) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreFileAssociationError(document.RootElement); + if (vectorStoreFileAssociationError == null) + { + return null; + } + return BinaryContent.Create(vectorStoreFileAssociationError, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreFileAssociationError(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileAssociationError(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreFileAssociationError.cs b/src/Generated/Models/VectorStoreFileAssociationError.cs index 638e7f527..c57800d5d 100644 --- a/src/Generated/Models/VectorStoreFileAssociationError.cs +++ b/src/Generated/Models/VectorStoreFileAssociationError.cs @@ -9,27 +9,29 @@ namespace OpenAI.VectorStores { public partial class VectorStoreFileAssociationError { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal VectorStoreFileAssociationError(VectorStoreFileAssociationErrorCode code, string message) { - Argument.AssertNotNull(message, nameof(message)); - Code = code; Message = message; } - internal VectorStoreFileAssociationError(VectorStoreFileAssociationErrorCode code, string message, IDictionary serializedAdditionalRawData) + internal VectorStoreFileAssociationError(VectorStoreFileAssociationErrorCode code, string message, IDictionary additionalBinaryDataProperties) { Code = code; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal VectorStoreFileAssociationError() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public VectorStoreFileAssociationErrorCode Code { get; } + public string Message { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs b/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs index 167ad6b2a..3046b192d 100644 --- a/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs +++ b/src/Generated/Models/VectorStoreFileAssociationErrorCode.cs @@ -4,35 +4,44 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { public readonly partial struct VectorStoreFileAssociationErrorCode : IEquatable { private readonly string _value; + private const string ServerErrorValue = "server_error"; + private const string UnsupportedFileValue = "unsupported_file"; + private const string InvalidFileValue = "invalid_file"; public VectorStoreFileAssociationErrorCode(string value) { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } + Argument.AssertNotNull(value, nameof(value)); - private const string ServerErrorValue = "server_error"; - private const string UnsupportedFileValue = "unsupported_file"; - private const string InvalidFileValue = "invalid_file"; + _value = value; + } public static VectorStoreFileAssociationErrorCode ServerError { get; } = new VectorStoreFileAssociationErrorCode(ServerErrorValue); + public static VectorStoreFileAssociationErrorCode UnsupportedFile { get; } = new VectorStoreFileAssociationErrorCode(UnsupportedFileValue); + public static VectorStoreFileAssociationErrorCode InvalidFile { get; } = new VectorStoreFileAssociationErrorCode(InvalidFileValue); + public static bool operator ==(VectorStoreFileAssociationErrorCode left, VectorStoreFileAssociationErrorCode right) => left.Equals(right); + public static bool operator !=(VectorStoreFileAssociationErrorCode left, VectorStoreFileAssociationErrorCode right) => !left.Equals(right); + public static implicit operator VectorStoreFileAssociationErrorCode(string value) => new VectorStoreFileAssociationErrorCode(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is VectorStoreFileAssociationErrorCode other && Equals(other); + public bool Equals(VectorStoreFileAssociationErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/VectorStoreFileAssociationStatus.Serialization.cs b/src/Generated/Models/VectorStoreFileAssociationStatus.Serialization.cs index fc493ac6a..49c9326c3 100644 --- a/src/Generated/Models/VectorStoreFileAssociationStatus.Serialization.cs +++ b/src/Generated/Models/VectorStoreFileAssociationStatus.Serialization.cs @@ -8,21 +8,33 @@ namespace OpenAI.VectorStores { internal static partial class VectorStoreFileAssociationStatusExtensions { - public static string ToSerialString(this VectorStoreFileAssociationStatus value) => value switch + public static string ToSerialString(this VectorStores.VectorStoreFileAssociationStatus value) => value switch { - VectorStoreFileAssociationStatus.InProgress => "in_progress", - VectorStoreFileAssociationStatus.Completed => "completed", - VectorStoreFileAssociationStatus.Cancelled => "cancelled", - VectorStoreFileAssociationStatus.Failed => "failed", + VectorStores.VectorStoreFileAssociationStatus.InProgress => "in_progress", + VectorStores.VectorStoreFileAssociationStatus.Completed => "completed", + VectorStores.VectorStoreFileAssociationStatus.Cancelled => "cancelled", + VectorStores.VectorStoreFileAssociationStatus.Failed => "failed", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreFileAssociationStatus value.") }; - public static VectorStoreFileAssociationStatus ToVectorStoreFileAssociationStatus(this string value) + public static VectorStores.VectorStoreFileAssociationStatus ToVectorStoreFileAssociationStatus(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "in_progress")) return VectorStoreFileAssociationStatus.InProgress; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "completed")) return VectorStoreFileAssociationStatus.Completed; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "cancelled")) return VectorStoreFileAssociationStatus.Cancelled; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "failed")) return VectorStoreFileAssociationStatus.Failed; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "in_progress")) + { + return VectorStores.VectorStoreFileAssociationStatus.InProgress; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "completed")) + { + return VectorStores.VectorStoreFileAssociationStatus.Completed; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "cancelled")) + { + return VectorStores.VectorStoreFileAssociationStatus.Cancelled; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "failed")) + { + return VectorStores.VectorStoreFileAssociationStatus.Failed; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreFileAssociationStatus value."); } } diff --git a/src/Generated/Models/VectorStoreFileCounts.Serialization.cs b/src/Generated/Models/VectorStoreFileCounts.Serialization.cs index 0a4998a0f..05a8d299b 100644 --- a/src/Generated/Models/VectorStoreFileCounts.Serialization.cs +++ b/src/Generated/Models/VectorStoreFileCounts.Serialization.cs @@ -7,48 +7,58 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreFileCounts : IJsonModel { + internal VectorStoreFileCounts() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreFileCounts)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("in_progress") != true) + if (_additionalBinaryDataProperties?.ContainsKey("in_progress") != true) { writer.WritePropertyName("in_progress"u8); writer.WriteNumberValue(InProgress); } - if (SerializedAdditionalRawData?.ContainsKey("completed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("completed") != true) { writer.WritePropertyName("completed"u8); writer.WriteNumberValue(Completed); } - if (SerializedAdditionalRawData?.ContainsKey("failed") != true) + if (_additionalBinaryDataProperties?.ContainsKey("failed") != true) { writer.WritePropertyName("failed"u8); writer.WriteNumberValue(Failed); } - if (SerializedAdditionalRawData?.ContainsKey("cancelled") != true) + if (_additionalBinaryDataProperties?.ContainsKey("cancelled") != true) { writer.WritePropertyName("cancelled"u8); writer.WriteNumberValue(Cancelled); } - if (SerializedAdditionalRawData?.ContainsKey("total") != true) + if (_additionalBinaryDataProperties?.ContainsKey("total") != true) { writer.WritePropertyName("total"u8); writer.WriteNumberValue(Total); } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -56,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -65,25 +75,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW #endif } } - writer.WriteEndObject(); } - VectorStoreFileCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreFileCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreFileCounts JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreFileCounts)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreFileCounts(document.RootElement, options); } - internal static VectorStoreFileCounts DeserializeVectorStoreFileCounts(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreFileCounts DeserializeVectorStoreFileCounts(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; @@ -93,55 +101,53 @@ internal static VectorStoreFileCounts DeserializeVectorStoreFileCounts(JsonEleme int failed = default; int cancelled = default; int total = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("in_progress"u8)) + if (prop.NameEquals("in_progress"u8)) { - inProgress = property.Value.GetInt32(); + inProgress = prop.Value.GetInt32(); continue; } - if (property.NameEquals("completed"u8)) + if (prop.NameEquals("completed"u8)) { - completed = property.Value.GetInt32(); + completed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("failed"u8)) + if (prop.NameEquals("failed"u8)) { - failed = property.Value.GetInt32(); + failed = prop.Value.GetInt32(); continue; } - if (property.NameEquals("cancelled"u8)) + if (prop.NameEquals("cancelled"u8)) { - cancelled = property.Value.GetInt32(); + cancelled = prop.Value.GetInt32(); continue; } - if (property.NameEquals("total"u8)) + if (prop.NameEquals("total"u8)) { - total = property.Value.GetInt32(); + total = prop.Value.GetInt32(); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; return new VectorStoreFileCounts( inProgress, completed, failed, cancelled, total, - serializedAdditionalRawData); + additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -151,15 +157,16 @@ BinaryData IPersistableModel.Write(ModelReaderWriterOptio } } - VectorStoreFileCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreFileCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreFileCounts 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreFileCounts(document.RootElement, options); } default: @@ -169,15 +176,20 @@ VectorStoreFileCounts IPersistableModel.Create(BinaryData string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreFileCounts FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreFileCounts vectorStoreFileCounts) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreFileCounts(document.RootElement); + if (vectorStoreFileCounts == null) + { + return null; + } + return BinaryContent.Create(vectorStoreFileCounts, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreFileCounts(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileCounts(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreFileCounts.cs b/src/Generated/Models/VectorStoreFileCounts.cs index 7d35eacce..412140d6e 100644 --- a/src/Generated/Models/VectorStoreFileCounts.cs +++ b/src/Generated/Models/VectorStoreFileCounts.cs @@ -9,7 +9,8 @@ namespace OpenAI.VectorStores { public partial class VectorStoreFileCounts { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + internal VectorStoreFileCounts(int inProgress, int completed, int failed, int cancelled, int total) { InProgress = inProgress; @@ -19,24 +20,30 @@ internal VectorStoreFileCounts(int inProgress, int completed, int failed, int ca Total = total; } - internal VectorStoreFileCounts(int inProgress, int completed, int failed, int cancelled, int total, IDictionary serializedAdditionalRawData) + internal VectorStoreFileCounts(int inProgress, int completed, int failed, int cancelled, int total, IDictionary additionalBinaryDataProperties) { InProgress = inProgress; Completed = completed; Failed = failed; Cancelled = cancelled; Total = total; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal VectorStoreFileCounts() - { + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public int InProgress { get; } + public int Completed { get; } + public int Failed { get; } + public int Cancelled { get; } + public int Total { get; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreFileStatusFilter.cs b/src/Generated/Models/VectorStoreFileStatusFilter.cs index 762b7f106..d7824a14c 100644 --- a/src/Generated/Models/VectorStoreFileStatusFilter.cs +++ b/src/Generated/Models/VectorStoreFileStatusFilter.cs @@ -4,37 +4,47 @@ using System; using System.ComponentModel; +using OpenAI; namespace OpenAI.VectorStores { public readonly partial struct VectorStoreFileStatusFilter : IEquatable { private readonly string _value; - - public VectorStoreFileStatusFilter(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - private const string InProgressValue = "in_progress"; private const string CompletedValue = "completed"; private const string FailedValue = "failed"; private const string CancelledValue = "cancelled"; + public VectorStoreFileStatusFilter(string value) + { + Argument.AssertNotNull(value, nameof(value)); + + _value = value; + } + public static VectorStoreFileStatusFilter InProgress { get; } = new VectorStoreFileStatusFilter(InProgressValue); + public static VectorStoreFileStatusFilter Completed { get; } = new VectorStoreFileStatusFilter(CompletedValue); + public static VectorStoreFileStatusFilter Failed { get; } = new VectorStoreFileStatusFilter(FailedValue); + public static VectorStoreFileStatusFilter Cancelled { get; } = new VectorStoreFileStatusFilter(CancelledValue); + public static bool operator ==(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => left.Equals(right); + public static bool operator !=(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => !left.Equals(right); + public static implicit operator VectorStoreFileStatusFilter(string value) => new VectorStoreFileStatusFilter(value); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is VectorStoreFileStatusFilter other && Equals(other); + public bool Equals(VectorStoreFileStatusFilter other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + public override string ToString() => _value; } } diff --git a/src/Generated/Models/VectorStoreModificationOptions.Serialization.cs b/src/Generated/Models/VectorStoreModificationOptions.Serialization.cs index 16e2ec490..ad9c7f889 100644 --- a/src/Generated/Models/VectorStoreModificationOptions.Serialization.cs +++ b/src/Generated/Models/VectorStoreModificationOptions.Serialization.cs @@ -7,6 +7,7 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.VectorStores { @@ -14,14 +15,19 @@ public partial class VectorStoreModificationOptions : IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(VectorStoreModificationOptions)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("name") != true && Optional.IsDefined(Name)) + if (Optional.IsDefined(Name) && _additionalBinaryDataProperties?.ContainsKey("name") != true) { if (Name != null) { @@ -30,22 +36,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } else { - writer.WriteNull("name"); + writer.WriteNull("name"u8); } } - if (SerializedAdditionalRawData?.ContainsKey("expires_after") != true && Optional.IsDefined(ExpirationPolicy)) - { - if (ExpirationPolicy != null) - { - writer.WritePropertyName("expires_after"u8); - writer.WriteObjectValue(ExpirationPolicy, options); - } - else - { - writer.WriteNull("expires_after"); - } - } - if (SerializedAdditionalRawData?.ContainsKey("metadata") != true && Optional.IsCollectionDefined(Metadata)) + if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true) { if (Metadata != null) { @@ -54,18 +48,35 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod foreach (var item in Metadata) { writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } writer.WriteStringValue(item.Value); } writer.WriteEndObject(); } else { - writer.WriteNull("metadata"); + writer.WriteNull("metadata"u8); + } + } + if (Optional.IsDefined(ExpirationPolicy) && _additionalBinaryDataProperties?.ContainsKey("expires_after") != true) + { + if (ExpirationPolicy != null) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpirationPolicy, options); + } + else + { + writer.WriteNull("expiresAfter"u8); } } - if (SerializedAdditionalRawData != null) + if (true && _additionalBinaryDataProperties != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _additionalBinaryDataProperties) { if (ModelSerializationExtensions.IsSentinelValue(item.Value)) { @@ -73,7 +84,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); + writer.WriteRawValue(item.Value); #else using (JsonDocument document = JsonDocument.Parse(item.Value)) { @@ -82,84 +93,87 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod #endif } } - writer.WriteEndObject(); } - VectorStoreModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreModificationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); + + protected virtual VectorStoreModificationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(VectorStoreModificationOptions)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeVectorStoreModificationOptions(document.RootElement, options); } - internal static VectorStoreModificationOptions DeserializeVectorStoreModificationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreModificationOptions DeserializeVectorStoreModificationOptions(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } string name = default; - VectorStoreExpirationPolicy expiresAfter = default; IDictionary metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + VectorStoreExpirationPolicy expirationPolicy = default; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("name"u8)) + if (prop.NameEquals("name"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { name = null; continue; } - name = property.Value.GetString(); + name = prop.Value.GetString(); continue; } - if (property.NameEquals("expires_after"u8)) + if (prop.NameEquals("metadata"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { - expiresAfter = null; continue; } - expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + Dictionary dictionary = new Dictionary(); + foreach (var prop0 in prop.Value.EnumerateObject()) + { + if (prop0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(prop0.Name, null); + } + else + { + dictionary.Add(prop0.Name, prop0.Value.GetString()); + } + } + metadata = dictionary; continue; } - if (property.NameEquals("metadata"u8)) + if (prop.NameEquals("expires_after"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + if (prop.Value.ValueKind == JsonValueKind.Null) { + expirationPolicy = null; continue; } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - metadata = dictionary; + expirationPolicy = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new VectorStoreModificationOptions(name, expiresAfter, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new VectorStoreModificationOptions(name, metadata ?? new ChangeTrackingDictionary(), expirationPolicy, additionalBinaryDataProperties); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -169,15 +183,16 @@ BinaryData IPersistableModel.Write(ModelReaderWr } } - VectorStoreModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + VectorStoreModificationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); + protected virtual VectorStoreModificationOptions 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeVectorStoreModificationOptions(document.RootElement, options); } default: @@ -187,15 +202,20 @@ VectorStoreModificationOptions IPersistableModel string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static VectorStoreModificationOptions FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(VectorStoreModificationOptions vectorStoreModificationOptions) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeVectorStoreModificationOptions(document.RootElement); + if (vectorStoreModificationOptions == null) + { + return null; + } + return BinaryContent.Create(vectorStoreModificationOptions, ModelSerializationExtensions.WireOptions); } - internal virtual BinaryContent ToBinaryContent() + public static explicit operator VectorStoreModificationOptions(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreModificationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/VectorStoreModificationOptions.cs b/src/Generated/Models/VectorStoreModificationOptions.cs index 8597db68c..a9a6d29b1 100644 --- a/src/Generated/Models/VectorStoreModificationOptions.cs +++ b/src/Generated/Models/VectorStoreModificationOptions.cs @@ -4,26 +4,35 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.VectorStores { public partial class VectorStoreModificationOptions { - internal IDictionary SerializedAdditionalRawData { get; set; } + private protected IDictionary _additionalBinaryDataProperties; + public VectorStoreModificationOptions() { Metadata = new ChangeTrackingDictionary(); } - internal VectorStoreModificationOptions(string name, VectorStoreExpirationPolicy expirationPolicy, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreModificationOptions(string name, IDictionary metadata, VectorStoreExpirationPolicy expirationPolicy, IDictionary additionalBinaryDataProperties) { Name = name; - ExpirationPolicy = expirationPolicy; Metadata = metadata; - SerializedAdditionalRawData = serializedAdditionalRawData; + ExpirationPolicy = expirationPolicy; + _additionalBinaryDataProperties = additionalBinaryDataProperties; } public string Name { get; set; } + public IDictionary Metadata { get; set; } + + internal IDictionary SerializedAdditionalRawData + { + get => _additionalBinaryDataProperties; + set => _additionalBinaryDataProperties = value; + } } } diff --git a/src/Generated/Models/VectorStoreStatus.Serialization.cs b/src/Generated/Models/VectorStoreStatus.Serialization.cs index c4417aef5..51e3ad31d 100644 --- a/src/Generated/Models/VectorStoreStatus.Serialization.cs +++ b/src/Generated/Models/VectorStoreStatus.Serialization.cs @@ -8,19 +8,28 @@ namespace OpenAI.VectorStores { internal static partial class VectorStoreStatusExtensions { - public static string ToSerialString(this VectorStoreStatus value) => value switch + public static string ToSerialString(this VectorStores.VectorStoreStatus value) => value switch { - VectorStoreStatus.Expired => "expired", - VectorStoreStatus.InProgress => "in_progress", - VectorStoreStatus.Completed => "completed", + VectorStores.VectorStoreStatus.Expired => "expired", + VectorStores.VectorStoreStatus.InProgress => "in_progress", + VectorStores.VectorStoreStatus.Completed => "completed", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreStatus value.") }; - public static VectorStoreStatus ToVectorStoreStatus(this string value) + public static VectorStores.VectorStoreStatus ToVectorStoreStatus(this string value) { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "expired")) return VectorStoreStatus.Expired; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "in_progress")) return VectorStoreStatus.InProgress; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "completed")) return VectorStoreStatus.Completed; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "expired")) + { + return VectorStores.VectorStoreStatus.Expired; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "in_progress")) + { + return VectorStores.VectorStoreStatus.InProgress; + } + if (StringComparer.OrdinalIgnoreCase.Equals(value, "completed")) + { + return VectorStores.VectorStoreStatus.Completed; + } throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VectorStoreStatus value."); } } diff --git a/src/Generated/Models/WeightsAndBiasesIntegration.Serialization.cs b/src/Generated/Models/WeightsAndBiasesIntegration.Serialization.cs index dfdc93fe7..893030090 100644 --- a/src/Generated/Models/WeightsAndBiasesIntegration.Serialization.cs +++ b/src/Generated/Models/WeightsAndBiasesIntegration.Serialization.cs @@ -7,102 +7,85 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using OpenAI; namespace OpenAI.FineTuning { internal partial class WeightsAndBiasesIntegration : IJsonModel { + internal WeightsAndBiasesIntegration() + { + } + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + 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(WeightsAndBiasesIntegration)} does not support writing '{format}' format."); } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("wandb") != true) + base.JsonModelWriteCore(writer, options); + if (_additionalBinaryDataProperties?.ContainsKey("wandb") != true) { writer.WritePropertyName("wandb"u8); writer.WriteObjectValue(Wandb, options); } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); } - WeightsAndBiasesIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + WeightsAndBiasesIntegration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (WeightsAndBiasesIntegration)JsonModelCreateCore(ref reader, options); + + protected override FineTuningIntegration JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { throw new FormatException($"The model {nameof(WeightsAndBiasesIntegration)} does not support reading '{format}' format."); } - using JsonDocument document = JsonDocument.ParseValue(ref reader); return DeserializeWeightsAndBiasesIntegration(document.RootElement, options); } - internal static WeightsAndBiasesIntegration DeserializeWeightsAndBiasesIntegration(JsonElement element, ModelReaderWriterOptions options = null) + internal static WeightsAndBiasesIntegration DeserializeWeightsAndBiasesIntegration(JsonElement element, ModelReaderWriterOptions options) { - options ??= ModelSerializationExtensions.WireOptions; - if (element.ValueKind == JsonValueKind.Null) { return null; } + string @type = "wandb"; + IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); InternalCreateFineTuningJobRequestWandbIntegrationWandb wandb = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) + foreach (var prop in element.EnumerateObject()) { - if (property.NameEquals("wandb"u8)) + if (prop.NameEquals("type"u8)) { - wandb = InternalCreateFineTuningJobRequestWandbIntegrationWandb.DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(property.Value, options); + @type = prop.Value.GetString(); continue; } - if (property.NameEquals("type"u8)) + if (prop.NameEquals("wandb"u8)) { - type = property.Value.GetString(); + wandb = InternalCreateFineTuningJobRequestWandbIntegrationWandb.DeserializeInternalCreateFineTuningJobRequestWandbIntegrationWandb(prop.Value, options); continue; } if (true) { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); } } - serializedAdditionalRawData = rawDataDictionary; - return new WeightsAndBiasesIntegration(type, serializedAdditionalRawData, wandb); + return new WeightsAndBiasesIntegration(@type, additionalBinaryDataProperties, wandb); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); + protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) + { + string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": @@ -112,15 +95,16 @@ BinaryData IPersistableModel.Write(ModelReaderWrite } } - WeightsAndBiasesIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + WeightsAndBiasesIntegration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (WeightsAndBiasesIntegration)PersistableModelCreateCore(data, options); + protected override FineTuningIntegration 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)) { - using JsonDocument document = JsonDocument.Parse(data); return DeserializeWeightsAndBiasesIntegration(document.RootElement, options); } default: @@ -130,15 +114,20 @@ WeightsAndBiasesIntegration IPersistableModel.Creat string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static new WeightsAndBiasesIntegration FromResponse(PipelineResponse response) + public static implicit operator BinaryContent(WeightsAndBiasesIntegration weightsAndBiasesIntegration) { - using var document = JsonDocument.Parse(response.Content); - return DeserializeWeightsAndBiasesIntegration(document.RootElement); + if (weightsAndBiasesIntegration == null) + { + return null; + } + return BinaryContent.Create(weightsAndBiasesIntegration, ModelSerializationExtensions.WireOptions); } - internal override BinaryContent ToBinaryContent() + public static explicit operator WeightsAndBiasesIntegration(ClientResult result) { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + using PipelineResponse response = result.GetRawResponse(); + using JsonDocument document = JsonDocument.Parse(response.Content); + return DeserializeWeightsAndBiasesIntegration(document.RootElement, ModelSerializationExtensions.WireOptions); } } } diff --git a/src/Generated/Models/WeightsAndBiasesIntegration.cs b/src/Generated/Models/WeightsAndBiasesIntegration.cs index 98fb23f82..7a9991f10 100644 --- a/src/Generated/Models/WeightsAndBiasesIntegration.cs +++ b/src/Generated/Models/WeightsAndBiasesIntegration.cs @@ -4,28 +4,24 @@ using System; using System.Collections.Generic; +using OpenAI; namespace OpenAI.FineTuning { internal partial class WeightsAndBiasesIntegration : FineTuningIntegration { - public WeightsAndBiasesIntegration(InternalCreateFineTuningJobRequestWandbIntegrationWandb wandb) + public WeightsAndBiasesIntegration(InternalCreateFineTuningJobRequestWandbIntegrationWandb wandb) : base("wandb") { Argument.AssertNotNull(wandb, nameof(wandb)); - Type = "wandb"; Wandb = wandb; } - internal WeightsAndBiasesIntegration(string type, IDictionary serializedAdditionalRawData, InternalCreateFineTuningJobRequestWandbIntegrationWandb wandb) : base(type, serializedAdditionalRawData) + internal WeightsAndBiasesIntegration(string @type, IDictionary additionalBinaryDataProperties, InternalCreateFineTuningJobRequestWandbIntegrationWandb wandb) : base(@type, additionalBinaryDataProperties) { Wandb = wandb; } - internal WeightsAndBiasesIntegration() - { - } - public InternalCreateFineTuningJobRequestWandbIntegrationWandb Wandb { get; } } } diff --git a/src/Generated/ModerationClient.RestClient.cs b/src/Generated/ModerationClient.RestClient.cs new file mode 100644 index 000000000..6830098b0 --- /dev/null +++ b/src/Generated/ModerationClient.RestClient.cs @@ -0,0 +1,34 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Moderations +{ + public partial class ModerationClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateModerationRequest(BinaryContent content, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/moderations", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", "application/json"); + request.Content = content; + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/ModerationClient.cs b/src/Generated/ModerationClient.cs index 5cfe31284..e9b11d1f4 100644 --- a/src/Generated/ModerationClient.cs +++ b/src/Generated/ModerationClient.cs @@ -5,41 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Moderations { - // Data plane generated sub-client. public partial class ModerationClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected ModerationClient() { } - internal PipelineMessage CreateCreateModerationRequest(BinaryContent content, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/moderations", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", "application/json"); - request.Content = content; - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/OpenAIClient.RestClient.cs b/src/Generated/OpenAIClient.RestClient.cs new file mode 100644 index 000000000..d4b5048e1 --- /dev/null +++ b/src/Generated/OpenAIClient.RestClient.cs @@ -0,0 +1,10 @@ +// + +#nullable disable + +namespace OpenAI +{ + public partial class OpenAIClient + { + } +} diff --git a/src/Generated/OpenAIClient.cs b/src/Generated/OpenAIClient.cs index 706a03969..6d07001cd 100644 --- a/src/Generated/OpenAIClient.cs +++ b/src/Generated/OpenAIClient.cs @@ -5,34 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading; -using OpenAI.Assistants; -using OpenAI.Audio; -using OpenAI.Batch; -using OpenAI.Chat; -using OpenAI.Embeddings; -using OpenAI.Files; -using OpenAI.FineTuning; -using OpenAI.Images; -using OpenAI.LegacyCompletions; -using OpenAI.Models; -using OpenAI.Moderations; -using OpenAI.RealtimeConversation; -using OpenAI.VectorStores; namespace OpenAI { - // Data plane generated client. public partial class OpenAIClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected OpenAIClient() { } + + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/OpenAIFileClient.RestClient.cs b/src/Generated/OpenAIFileClient.RestClient.cs new file mode 100644 index 000000000..75e133f8b --- /dev/null +++ b/src/Generated/OpenAIFileClient.RestClient.cs @@ -0,0 +1,102 @@ +// + +#nullable disable + +using System.ClientModel; +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Files +{ + public partial class OpenAIFileClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateCreateFileRequest(BinaryContent content, string contentType, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "POST"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + request.Headers.Set("Content-Type", contentType); + request.Content = content; + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListFilesRequest(string purpose, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files", false); + if (purpose != null) + { + uri.AppendQuery("purpose", purpose, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateRetrieveFileRequest(string fileId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDeleteFileRequest(string fileId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "DELETE"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDownloadFileRequest(string fileId, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + uri.AppendPath("/content", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/OpenAIFileClient.cs b/src/Generated/OpenAIFileClient.cs index 8e52efabb..bdab19cdd 100644 --- a/src/Generated/OpenAIFileClient.cs +++ b/src/Generated/OpenAIFileClient.cs @@ -5,109 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Files { - // Data plane generated sub-client. public partial class OpenAIFileClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected OpenAIFileClient() { } - internal PipelineMessage CreateCreateFileRequest(BinaryContent content, string contentType, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "POST"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/files", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - request.Headers.Set("Content-Type", contentType); - request.Content = content; - message.Apply(options); - return message; - } - - internal PipelineMessage CreateGetFilesRequest(string purpose, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/files", false); - if (purpose != null) - { - uri.AppendQuery("purpose", purpose, true); - } - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateRetrieveFileRequest(string fileId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/files/", false); - uri.AppendPath(fileId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDeleteFileRequest(string fileId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "DELETE"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/files/", false); - uri.AppendPath(fileId, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDownloadFileRequest(string fileId, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/files/", false); - uri.AppendPath(fileId, true); - uri.AppendPath("/content", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/OpenAIModelClient.RestClient.cs b/src/Generated/OpenAIModelClient.RestClient.cs new file mode 100644 index 000000000..a94220acb --- /dev/null +++ b/src/Generated/OpenAIModelClient.RestClient.cs @@ -0,0 +1,63 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.Models +{ + public partial class OpenAIModelClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateListModelsRequest(RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/models", false); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateRetrieveModelRequest(string model, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/models/", false); + uri.AppendPath(model, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateDeleteModelRequest(string model, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "DELETE"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/models/", false); + uri.AppendPath(model, true); + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/OpenAIModelClient.cs b/src/Generated/OpenAIModelClient.cs index 0296874f0..77aafebbd 100644 --- a/src/Generated/OpenAIModelClient.cs +++ b/src/Generated/OpenAIModelClient.cs @@ -5,71 +5,20 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Threading.Tasks; namespace OpenAI.Models { - // Data plane generated sub-client. public partial class OpenAIModelClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected OpenAIModelClient() { } - internal PipelineMessage CreateGetModelsRequest(RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/models", false); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateRetrieveModelRequest(string model, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "GET"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/models/", false); - uri.AppendPath(model, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - internal PipelineMessage CreateDeleteModelRequest(string model, RequestOptions options) - { - var message = _pipeline.CreateMessage(); - message.ResponseClassifier = PipelineMessageClassifier200; - var request = message.Request; - request.Method = "DELETE"; - var uri = new ClientUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/models/", false); - uri.AppendPath(model, true); - request.Uri = uri.ToUri(); - request.Headers.Set("Accept", "application/json"); - message.Apply(options); - return message; - } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/OpenAIModelFactory.cs b/src/Generated/OpenAIModelFactory.cs index ae5b5906c..10419b84a 100644 --- a/src/Generated/OpenAIModelFactory.cs +++ b/src/Generated/OpenAIModelFactory.cs @@ -9,7 +9,9 @@ using OpenAI.Audio; using OpenAI.Chat; using OpenAI.Embeddings; +using OpenAI.Files; using OpenAI.Images; +using OpenAI.Models; using OpenAI.Moderations; using OpenAI.RealtimeConversation; using OpenAI.VectorStores; @@ -18,133 +20,630 @@ namespace OpenAI { internal static partial class OpenAIModelFactory { + public static OpenAIFile OpenAIFile(string id = default, DateTimeOffset createdAt = default, string filename = default, Files.FilePurpose purpose = default, InternalOpenAIFileObject @object = default, int? sizeInBytes = default, Files.FileStatus status = default, string statusDetails = default) + { + + return new OpenAIFile( + id, + createdAt, + filename, + purpose, + @object, + sizeInBytes, + status, + statusDetails, + additionalBinaryDataProperties: null); + } + + public static VectorStore VectorStore(string id = default, DateTimeOffset createdAt = default, string name = default, int usageBytes = default, VectorStoreFileCounts fileCounts = default, VectorStores.VectorStoreStatus status = default, DateTimeOffset? expiresAt = default, DateTimeOffset? lastActiveAt = default, IReadOnlyDictionary metadata = default, InternalVectorStoreObjectObject @object = default, VectorStoreExpirationPolicy expirationPolicy = default) + { + metadata ??= new ChangeTrackingDictionary(); + + return new VectorStore( + id, + createdAt, + name, + usageBytes, + fileCounts, + status, + expiresAt, + lastActiveAt, + metadata, + @object, + expirationPolicy, + additionalBinaryDataProperties: null); + } + public static VectorStoreFileCounts VectorStoreFileCounts(int inProgress = default, int completed = default, int failed = default, int cancelled = default, int total = default) { + return new VectorStoreFileCounts( inProgress, completed, failed, cancelled, total, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); + } + + public static VectorStoreExpirationPolicy VectorStoreExpirationPolicy(VectorStores.VectorStoreExpirationAnchor anchor = default, int days = default) + { + + return new VectorStoreExpirationPolicy(anchor, days, serializedAdditionalRawData: null); + } + + public static VectorStoreCreationOptions VectorStoreCreationOptions(IEnumerable fileIds = default, string name = default, IDictionary metadata = default, VectorStoreExpirationPolicy expirationPolicy = default, FileChunkingStrategy chunkingStrategy = default) + { + fileIds ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + + return new VectorStoreCreationOptions( + fileIds?.ToList(), + name, + metadata, + expirationPolicy, + chunkingStrategy, + additionalBinaryDataProperties: null); + } + + public static VectorStoreModificationOptions VectorStoreModificationOptions(string name = default, IDictionary metadata = default, VectorStoreExpirationPolicy expirationPolicy = default) + { + metadata ??= new ChangeTrackingDictionary(); + + return new VectorStoreModificationOptions(name, metadata, expirationPolicy, additionalBinaryDataProperties: null); + } + + public static VectorStoreDeletionResult VectorStoreDeletionResult(bool deleted = default, string vectorStoreId = default, InternalDeleteVectorStoreResponseObject @object = default) + { + + return new VectorStoreDeletionResult(deleted, vectorStoreId, @object, additionalBinaryDataProperties: null); + } + + public static VectorStoreFileAssociation VectorStoreFileAssociation(DateTimeOffset createdAt = default, string vectorStoreId = default, VectorStores.VectorStoreFileAssociationStatus status = default, VectorStoreFileAssociationError lastError = default, InternalVectorStoreFileObjectObject @object = default, string fileId = default, int size = default, FileChunkingStrategy chunkingStrategy = default) + { + + return new VectorStoreFileAssociation( + createdAt, + vectorStoreId, + status, + lastError, + @object, + fileId, + size, + chunkingStrategy, + additionalBinaryDataProperties: null); + } + + public static VectorStoreFileAssociationError VectorStoreFileAssociationError(VectorStoreFileAssociationErrorCode code = default, string message = default) + { + + return new VectorStoreFileAssociationError(code, message, additionalBinaryDataProperties: null); + } + + public static StaticFileChunkingStrategy StaticFileChunkingStrategy(InternalStaticChunkingStrategyDetails internalDetails = default) + { + + return new StaticFileChunkingStrategy("static", additionalBinaryDataProperties: null, internalDetails); + } + + public static FileChunkingStrategy FileChunkingStrategy(string @type = default) + { + + return new InternalUnknownFileChunkingStrategyResponseParamProxy(@type, additionalBinaryDataProperties: null); + } + + public static FileFromStoreRemovalResult FileFromStoreRemovalResult(string fileId = default, bool removed = default, InternalDeleteVectorStoreFileResponseObject @object = default) + { + + return new FileFromStoreRemovalResult(fileId, removed, @object, additionalBinaryDataProperties: null); + } + + public static VectorStoreBatchFileJob VectorStoreBatchFileJob(DateTimeOffset createdAt = default, string vectorStoreId = default, VectorStoreBatchFileJobStatus status = default, string batchId = default, VectorStoreFileCounts fileCounts = default, object @object = default) + { + + return new VectorStoreBatchFileJob( + createdAt, + vectorStoreId, + status, + batchId, + fileCounts, + @object, + additionalBinaryDataProperties: null); } - public static VectorStoreFileAssociationError VectorStoreFileAssociationError(VectorStoreFileAssociationErrorCode code = default, string message = null) + public static ThreadCreationOptions ThreadCreationOptions(IDictionary metadata = default, ToolResources toolResources = default, IEnumerable internalMessages = default) { - return new VectorStoreFileAssociationError(code, message, serializedAdditionalRawData: null); + metadata ??= new ChangeTrackingDictionary(); + internalMessages ??= new ChangeTrackingList(); + + return new ThreadCreationOptions(metadata, toolResources, internalMessages?.ToList(), additionalBinaryDataProperties: null); } - public static RunError RunError(RunErrorCode code = default, string message = null) + public static MessageCreationOptions MessageCreationOptions(IEnumerable attachments = default, IDictionary metadata = default, Assistants.MessageRole role = default, IEnumerable content = default) { - return new RunError(code, message, serializedAdditionalRawData: null); + attachments ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + content ??= new ChangeTrackingList(); + + return new MessageCreationOptions(attachments?.ToList(), metadata, role, content?.ToList(), additionalBinaryDataProperties: null); } - public static RunIncompleteDetails RunIncompleteDetails(RunIncompleteReason? reason = null) + public static MessageCreationAttachment MessageCreationAttachment(string fileId = default, IEnumerable tools = default) { - return new RunIncompleteDetails(reason, serializedAdditionalRawData: null); + tools ??= new ChangeTrackingList(); + + return new MessageCreationAttachment(fileId, tools?.ToList(), additionalBinaryDataProperties: null); + } + + public static CodeInterpreterToolDefinition CodeInterpreterToolDefinition() + { + + return new CodeInterpreterToolDefinition("code_interpreter", additionalBinaryDataProperties: null); + } + + public static ToolDefinition ToolDefinition(string @type = default) + { + + return new UnknownAssistantToolDefinition(@type, additionalBinaryDataProperties: null); + } + + public static FileSearchToolDefinition FileSearchToolDefinition(InternalAssistantToolsFileSearchFileSearch fileSearch = default) + { + + return new FileSearchToolDefinition("file_search", additionalBinaryDataProperties: null, fileSearch); + } + + public static FileSearchRankingOptions FileSearchRankingOptions(FileSearchRanker? ranker = default, float scoreThreshold = default) + { + + return new FileSearchRankingOptions(ranker, scoreThreshold, serializedAdditionalRawData: null); + } + + public static FunctionToolDefinition FunctionToolDefinition(string @type = default, InternalFunctionDefinition function = default) + { + + return new FunctionToolDefinition(@type, serializedAdditionalRawData: null, function); + } + + public static FileSearchToolResources FileSearchToolResources(IEnumerable vectorStoreIds = default, IEnumerable newVectorStores = default) + { + vectorStoreIds ??= new ChangeTrackingList(); + newVectorStores ??= new ChangeTrackingList(); + + return new FileSearchToolResources(vectorStoreIds?.ToList(), newVectorStores?.ToList(), additionalBinaryDataProperties: null); + } + + public static VectorStoreCreationHelper VectorStoreCreationHelper(IEnumerable fileIds = default, IDictionary metadata = default, FileChunkingStrategy chunkingStrategy = default) + { + fileIds ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + + return new VectorStoreCreationHelper(fileIds?.ToList(), metadata, chunkingStrategy, additionalBinaryDataProperties: null); + } + + public static RunTruncationStrategy RunTruncationStrategy(int? lastMessages = default, InternalTruncationObjectType @type = default) + { + + return new RunTruncationStrategy(lastMessages, @type, additionalBinaryDataProperties: null); + } + + public static ToolConstraint ToolConstraint(InternalAssistantsNamedToolChoiceFunction function = default, string objectType = default) + { + + return new ToolConstraint(function, objectType, additionalBinaryDataProperties: null); + } + + public static ThreadRun ThreadRun(string id = default, DateTimeOffset createdAt = default, string threadId = default, string assistantId = default, RunStatus status = default, RunError lastError = default, DateTimeOffset? expiresAt = default, DateTimeOffset? startedAt = default, DateTimeOffset? cancelledAt = default, DateTimeOffset? failedAt = default, DateTimeOffset? completedAt = default, RunIncompleteDetails incompleteDetails = default, string model = default, string instructions = default, IEnumerable tools = default, IReadOnlyDictionary metadata = default, RunTokenUsage usage = default, float? temperature = default, RunTruncationStrategy truncationStrategy = default, InternalRunObjectObject @object = default, AssistantResponseFormat responseFormat = default, ToolConstraint toolConstraint = default, float? nucleusSamplingFactor = default, bool? allowParallelToolCalls = default, int? maxInputTokenCount = default, int? maxOutputTokenCount = default, InternalRunRequiredAction internalRequiredAction = default) + { + tools ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + + return new ThreadRun( + id, + createdAt, + threadId, + assistantId, + status, + lastError, + expiresAt, + startedAt, + cancelledAt, + failedAt, + completedAt, + incompleteDetails, + model, + instructions, + tools?.ToList(), + metadata, + usage, + temperature, + truncationStrategy, + @object, + responseFormat, + toolConstraint, + nucleusSamplingFactor, + allowParallelToolCalls, + maxInputTokenCount, + maxOutputTokenCount, + internalRequiredAction, + additionalBinaryDataProperties: null); + } + + public static RunError RunError(RunErrorCode code = default, string message = default) + { + + return new RunError(code, message, additionalBinaryDataProperties: null); + } + + public static RunIncompleteDetails RunIncompleteDetails(RunIncompleteReason? reason = default) + { + + return new RunIncompleteDetails(reason, additionalBinaryDataProperties: null); } public static RunTokenUsage RunTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default) { - return new RunTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, serializedAdditionalRawData: null); + + return new RunTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, additionalBinaryDataProperties: null); } - public static RunStepToolCall RunStepToolCall(string id = null) + public static RunCreationOptions RunCreationOptions(string assistantId = default, bool? stream = default, AssistantResponseFormat responseFormat = default, string modelOverride = default, string instructionsOverride = default, string additionalInstructions = default, IEnumerable internalMessages = default, bool? allowParallelToolCalls = default, IEnumerable toolsOverride = default, IDictionary metadata = default, float? temperature = default, float? nucleusSamplingFactor = default, int? maxInputTokenCount = default, int? maxOutputTokenCount = default, RunTruncationStrategy truncationStrategy = default, ToolConstraint toolConstraint = default) { - return new UnknownRunStepDetailsToolCallsObjectToolCallsObject(default, id, serializedAdditionalRawData: null); + internalMessages ??= new ChangeTrackingList(); + toolsOverride ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + + return new RunCreationOptions( + assistantId, + stream, + responseFormat, + modelOverride, + instructionsOverride, + additionalInstructions, + internalMessages?.ToList(), + allowParallelToolCalls, + toolsOverride?.ToList(), + metadata, + temperature, + nucleusSamplingFactor, + maxInputTokenCount, + maxOutputTokenCount, + truncationStrategy, + toolConstraint, + additionalBinaryDataProperties: null); } - public static RunStepFileSearchResult RunStepFileSearchResult(string fileId = null, string fileName = null, float score = default, IEnumerable content = null) + public static RunModificationOptions RunModificationOptions(IDictionary metadata = default) { - content ??= new List(); + metadata ??= new ChangeTrackingDictionary(); - return new RunStepFileSearchResult(fileId, fileName, score, content?.ToList(), serializedAdditionalRawData: null); + return new RunModificationOptions(metadata, additionalBinaryDataProperties: null); } - public static RunStepFileSearchResultContent RunStepFileSearchResultContent(RunStepFileSearchResultContentKind kind = default, string text = null) + public static ToolOutput ToolOutput(string toolCallId = default, string output = default) { - return new RunStepFileSearchResultContent(kind, text, serializedAdditionalRawData: null); + + return new ToolOutput(toolCallId, output, additionalBinaryDataProperties: null); } - public static RunStepError RunStepError(RunStepErrorCode code = default, string message = null) + public static RunStep RunStep(string id = default, DateTimeOffset createdAt = default, string assistantId = default, string threadId = default, string runId = default, RunStepStatus status = default, RunStepError lastError = default, DateTimeOffset? expiredAt = default, DateTimeOffset? cancelledAt = default, DateTimeOffset? failedAt = default, DateTimeOffset? completedAt = default, IReadOnlyDictionary metadata = default, RunStepTokenUsage usage = default, InternalRunStepObjectObject @object = default, Assistants.RunStepKind kind = default, RunStepDetails details = default) { - return new RunStepError(code, message, serializedAdditionalRawData: null); + metadata ??= new ChangeTrackingDictionary(); + + return new RunStep( + id, + createdAt, + assistantId, + threadId, + runId, + status, + lastError, + expiredAt, + cancelledAt, + failedAt, + completedAt, + metadata, + usage, + @object, + kind, + details, + additionalBinaryDataProperties: null); + } + + public static RunStepDetails RunStepDetails(string @type = default) + { + + return new UnknownRunStepObjectStepDetails(@type, additionalBinaryDataProperties: null); + } + + public static RunStepToolCall RunStepToolCall(string id = default, string kind = default) + { + + return new UnknownRunStepDetailsToolCallsObjectToolCallsObject(id, kind.ToRunStepToolCallKind(), additionalBinaryDataProperties: null); + } + + public static RunStepCodeInterpreterOutput RunStepCodeInterpreterOutput(string @type = default) + { + + return new UnknownRunStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(@type, additionalBinaryDataProperties: null); + } + + public static RunStepFileSearchResult RunStepFileSearchResult(string fileId = default, string fileName = default, float score = default, IEnumerable content = default) + { + content ??= new ChangeTrackingList(); + + return new RunStepFileSearchResult(fileId, fileName, score, content?.ToList(), additionalBinaryDataProperties: null); + } + + public static RunStepFileSearchResultContent RunStepFileSearchResultContent(string text = default, Assistants.RunStepFileSearchResultContentKind kind = default) + { + + return new RunStepFileSearchResultContent(text, kind, additionalBinaryDataProperties: null); + } + + public static RunStepError RunStepError(RunStepErrorCode code = default, string message = default) + { + + return new RunStepError(code, message, additionalBinaryDataProperties: null); } public static RunStepTokenUsage RunStepTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default) { - return new RunStepTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, serializedAdditionalRawData: null); + + return new RunStepTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, additionalBinaryDataProperties: null); + } + + public static AssistantThread AssistantThread(string id = default, DateTimeOffset createdAt = default, IReadOnlyDictionary metadata = default, InternalThreadObjectObject @object = default, ToolResources toolResources = default) + { + metadata ??= new ChangeTrackingDictionary(); + + return new AssistantThread( + id, + createdAt, + metadata, + @object, + toolResources, + additionalBinaryDataProperties: null); + } + + public static ThreadModificationOptions ThreadModificationOptions(IDictionary metadata = default, ToolResources toolResources = default) + { + metadata ??= new ChangeTrackingDictionary(); + + return new ThreadModificationOptions(metadata, toolResources, additionalBinaryDataProperties: null); + } + + public static ThreadDeletionResult ThreadDeletionResult(bool deleted = default, string threadId = default, InternalDeleteThreadResponseObject @object = default) + { + + return new ThreadDeletionResult(deleted, threadId, @object, additionalBinaryDataProperties: null); + } + + public static ConversationSessionOptions ConversationSessionOptions(string instructions = default, ConversationVoice? voice = default, ConversationAudioFormat? inputAudioFormat = default, ConversationAudioFormat? outputAudioFormat = default, IEnumerable tools = default, float? temperature = default, ConversationTurnDetectionOptions turnDetectionOptions = default, ConversationInputTranscriptionOptions inputTranscriptionOptions = default, IEnumerable internalModalities = default, BinaryData internalToolChoice = default, BinaryData maxResponseOutputTokens = default) + { + tools ??= new ChangeTrackingList(); + internalModalities ??= new ChangeTrackingList(); + + return new ConversationSessionOptions( + instructions, + voice, + inputAudioFormat, + outputAudioFormat, + tools?.ToList(), + temperature, + turnDetectionOptions, + inputTranscriptionOptions, + internalModalities?.ToList(), + internalToolChoice, + maxResponseOutputTokens, + additionalBinaryDataProperties: null); + } + + public static ConversationInputTranscriptionOptions ConversationInputTranscriptionOptions(ConversationTranscriptionModel? model = default) + { + + return new ConversationInputTranscriptionOptions(model, additionalBinaryDataProperties: null); + } + + public static ConversationTurnDetectionOptions ConversationTurnDetectionOptions(string kind = default) + { + + return new UnknownRealtimeTurnDetection(kind.ToConversationTurnDetectionKind(), additionalBinaryDataProperties: null); + } + + public static ConversationTool ConversationTool(string kind = default) + { + + return new UnknownRealtimeTool(new ConversationToolKind(kind), additionalBinaryDataProperties: null); + } + + public static ConversationFunctionTool ConversationFunctionTool(ConversationToolKind kind = default, string name = default, string description = default, BinaryData parameters = default) + { + + return new ConversationFunctionTool(kind, serializedAdditionalRawData: null, name, description, parameters); + } + + public static ConversationItem ConversationItem(string @type = default, string id = default) + { + + return new UnknownRealtimeRequestItem(new InternalRealtimeItemType(@type), id, additionalBinaryDataProperties: null); + } + + public static ConversationContentPart ConversationContentPart(string kind = default) + { + + return new UnknownRealtimeContentPart(new ConversationContentPartKind(kind), additionalBinaryDataProperties: null); + } + + public static ConversationUpdate ConversationUpdate(string eventId = default, string kind = default) + { + + return new UnknownRealtimeServerEvent(eventId, kind.ToConversationUpdateKind(), additionalBinaryDataProperties: null); + } + + public static ConversationErrorUpdate ConversationErrorUpdate(string eventId = default, InternalRealtimeServerEventErrorError error = default) + { + + return new ConversationErrorUpdate(eventId, RealtimeConversation.ConversationUpdateKind.Error, additionalBinaryDataProperties: null, error); + } + + public static ConversationSessionStartedUpdate ConversationSessionStartedUpdate(string eventId = default, InternalRealtimeResponseSession internalSession = default) + { + + return new ConversationSessionStartedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.SessionStarted, additionalBinaryDataProperties: null, internalSession); } - public static ConversationUpdate ConversationUpdate(string eventId = null) + public static ConversationSessionConfiguredUpdate ConversationSessionConfiguredUpdate(string eventId = default, InternalRealtimeResponseSession internalSession = default) { - return new UnknownRealtimeServerEvent(default, eventId, serializedAdditionalRawData: null); + + return new ConversationSessionConfiguredUpdate(eventId, RealtimeConversation.ConversationUpdateKind.SessionConfigured, additionalBinaryDataProperties: null, internalSession); } - public static ConversationInputAudioCommittedUpdate ConversationInputAudioCommittedUpdate(string eventId = null, string previousItemId = null, string itemId = null) + public static ConversationInputAudioCommittedUpdate ConversationInputAudioCommittedUpdate(string eventId = default, string previousItemId = default, string itemId = default) { - return new ConversationInputAudioCommittedUpdate(ConversationUpdateKind.InputAudioCommitted, eventId, serializedAdditionalRawData: null, previousItemId, itemId); + + return new ConversationInputAudioCommittedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.InputAudioCommitted, additionalBinaryDataProperties: null, previousItemId, itemId); } - public static ConversationInputAudioClearedUpdate ConversationInputAudioClearedUpdate(string eventId = null) + public static ConversationInputAudioClearedUpdate ConversationInputAudioClearedUpdate(string eventId = default) { - return new ConversationInputAudioClearedUpdate(ConversationUpdateKind.InputAudioCleared, eventId, serializedAdditionalRawData: null); + + return new ConversationInputAudioClearedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.InputAudioCleared, additionalBinaryDataProperties: null); } - public static ConversationInputTranscriptionFinishedUpdate ConversationInputTranscriptionFinishedUpdate(string eventId = null, string itemId = null, int contentIndex = default, string transcript = null) + public static ConversationInputSpeechStartedUpdate ConversationInputSpeechStartedUpdate(string eventId = default, string itemId = default, int audioStartMs = default) { + + return new ConversationInputSpeechStartedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.InputSpeechStarted, additionalBinaryDataProperties: null, itemId, audioStartMs); + } + + public static ConversationInputSpeechFinishedUpdate ConversationInputSpeechFinishedUpdate(string eventId = default, string itemId = default, int audioEndMs = default) + { + + return new ConversationInputSpeechFinishedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.InputSpeechStopped, additionalBinaryDataProperties: null, itemId, audioEndMs); + } + + public static ConversationItemCreatedUpdate ConversationItemCreatedUpdate(string eventId = default, string previousItemId = default, InternalRealtimeResponseItem internalItem = default) + { + + return new ConversationItemCreatedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.ItemCreated, additionalBinaryDataProperties: null, previousItemId, internalItem); + } + + public static ConversationInputTranscriptionFinishedUpdate ConversationInputTranscriptionFinishedUpdate(string eventId = default, string itemId = default, int contentIndex = default, string transcript = default) + { + return new ConversationInputTranscriptionFinishedUpdate( - ConversationUpdateKind.InputTranscriptionFinished, eventId, - serializedAdditionalRawData: null, + RealtimeConversation.ConversationUpdateKind.InputTranscriptionFinished, + additionalBinaryDataProperties: null, itemId, contentIndex, transcript); } - public static ConversationItemTruncatedUpdate ConversationItemTruncatedUpdate(string eventId = null, string itemId = null, int contentIndex = default, int audioEndMs = default) + public static ConversationInputTranscriptionFailedUpdate ConversationInputTranscriptionFailedUpdate(string eventId = default, string itemId = default, int contentIndex = default, InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError error = default) { + + return new ConversationInputTranscriptionFailedUpdate( + eventId, + RealtimeConversation.ConversationUpdateKind.InputTranscriptionFailed, + additionalBinaryDataProperties: null, + itemId, + contentIndex, + error); + } + + public static ConversationItemTruncatedUpdate ConversationItemTruncatedUpdate(string eventId = default, string itemId = default, int contentIndex = default, int audioEndMs = default) + { + return new ConversationItemTruncatedUpdate( - ConversationUpdateKind.ItemTruncated, eventId, - serializedAdditionalRawData: null, + RealtimeConversation.ConversationUpdateKind.ItemTruncated, + additionalBinaryDataProperties: null, itemId, contentIndex, audioEndMs); } - public static ConversationItemDeletedUpdate ConversationItemDeletedUpdate(string eventId = null, string itemId = null) + public static ConversationItemDeletedUpdate ConversationItemDeletedUpdate(string eventId = default, string itemId = default) { - return new ConversationItemDeletedUpdate(ConversationUpdateKind.ItemDeleted, eventId, serializedAdditionalRawData: null, itemId); + + return new ConversationItemDeletedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.ItemDeleted, additionalBinaryDataProperties: null, itemId); } - public static ConversationTokenUsage ConversationTokenUsage(int totalTokens = default, int inputTokens = default, int outputTokens = default, ConversationInputTokenUsageDetails inputTokenDetails = null, ConversationOutputTokenUsageDetails outputTokenDetails = null) + public static ConversationResponseStartedUpdate ConversationResponseStartedUpdate(string eventId = default, InternalRealtimeResponse internalResponse = default) { + + return new ConversationResponseStartedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.ResponseStarted, additionalBinaryDataProperties: null, internalResponse); + } + + public static ConversationStatusDetails ConversationStatusDetails(string statusKind = default) + { + + return new UnknownRealtimeResponseStatusDetails(new ConversationStatus(statusKind), additionalBinaryDataProperties: null); + } + + public static ConversationTokenUsage ConversationTokenUsage(int totalTokens = default, int inputTokens = default, int outputTokens = default, ConversationInputTokenUsageDetails inputTokenDetails = default, ConversationOutputTokenUsageDetails outputTokenDetails = default) + { + return new ConversationTokenUsage( totalTokens, inputTokens, outputTokens, inputTokenDetails, outputTokenDetails, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } public static ConversationInputTokenUsageDetails ConversationInputTokenUsageDetails(int cachedTokens = default, int textTokens = default, int audioTokens = default) { - return new ConversationInputTokenUsageDetails(cachedTokens, textTokens, audioTokens, serializedAdditionalRawData: null); + + return new ConversationInputTokenUsageDetails(cachedTokens, textTokens, audioTokens, additionalBinaryDataProperties: null); } public static ConversationOutputTokenUsageDetails ConversationOutputTokenUsageDetails(int textTokens = default, int audioTokens = default) { - return new ConversationOutputTokenUsageDetails(textTokens, audioTokens, serializedAdditionalRawData: null); + + return new ConversationOutputTokenUsageDetails(textTokens, audioTokens, additionalBinaryDataProperties: null); + } + + public static ConversationResponseFinishedUpdate ConversationResponseFinishedUpdate(string eventId = default, InternalRealtimeResponse internalResponse = default) + { + + return new ConversationResponseFinishedUpdate(eventId, RealtimeConversation.ConversationUpdateKind.ResponseFinished, additionalBinaryDataProperties: null, internalResponse); + } + + public static ConversationItemStreamingStartedUpdate ConversationItemStreamingStartedUpdate(string eventId = default, string responseId = default, int itemIndex = default, InternalRealtimeResponseItem internalItem = default) + { + + return new ConversationItemStreamingStartedUpdate( + eventId, + RealtimeConversation.ConversationUpdateKind.ItemStreamingStarted, + additionalBinaryDataProperties: null, + responseId, + itemIndex, + internalItem); + } + + public static ConversationItemStreamingFinishedUpdate ConversationItemStreamingFinishedUpdate(string eventId = default, string responseId = default, int outputIndex = default, InternalRealtimeResponseItem internalItem = default) + { + + return new ConversationItemStreamingFinishedUpdate( + eventId, + RealtimeConversation.ConversationUpdateKind.ItemStreamingFinished, + additionalBinaryDataProperties: null, + responseId, + outputIndex, + internalItem); } - public static ConversationItemStreamingTextFinishedUpdate ConversationItemStreamingTextFinishedUpdate(string eventId = null, string responseId = null, string itemId = null, int outputIndex = default, int contentIndex = default, string text = null) + public static ConversationItemStreamingTextFinishedUpdate ConversationItemStreamingTextFinishedUpdate(string eventId = default, string responseId = default, string itemId = default, int outputIndex = default, int contentIndex = default, string text = default) { + return new ConversationItemStreamingTextFinishedUpdate( - ConversationUpdateKind.ItemStreamingPartTextFinished, eventId, - serializedAdditionalRawData: null, + RealtimeConversation.ConversationUpdateKind.ItemStreamingPartTextFinished, + additionalBinaryDataProperties: null, responseId, itemId, outputIndex, @@ -152,12 +651,13 @@ public static ConversationItemStreamingTextFinishedUpdate ConversationItemStream text); } - public static ConversationItemStreamingAudioTranscriptionFinishedUpdate ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventId = null, string responseId = null, string itemId = null, int outputIndex = default, int contentIndex = default, string transcript = null) + public static ConversationItemStreamingAudioTranscriptionFinishedUpdate ConversationItemStreamingAudioTranscriptionFinishedUpdate(string eventId = default, string responseId = default, string itemId = default, int outputIndex = default, int contentIndex = default, string transcript = default) { + return new ConversationItemStreamingAudioTranscriptionFinishedUpdate( - ConversationUpdateKind.ItemStreamingPartAudioTranscriptionFinished, eventId, - serializedAdditionalRawData: null, + RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioTranscriptionFinished, + additionalBinaryDataProperties: null, responseId, itemId, outputIndex, @@ -165,160 +665,604 @@ public static ConversationItemStreamingAudioTranscriptionFinishedUpdate Conversa transcript); } - public static ConversationItemStreamingAudioFinishedUpdate ConversationItemStreamingAudioFinishedUpdate(string eventId = null, string responseId = null, string itemId = null, int outputIndex = default, int contentIndex = default) + public static ConversationItemStreamingAudioFinishedUpdate ConversationItemStreamingAudioFinishedUpdate(string eventId = default, string responseId = default, string itemId = default, int outputIndex = default, int contentIndex = default) { + return new ConversationItemStreamingAudioFinishedUpdate( - ConversationUpdateKind.ItemStreamingPartAudioFinished, eventId, - serializedAdditionalRawData: null, + RealtimeConversation.ConversationUpdateKind.ItemStreamingPartAudioFinished, + additionalBinaryDataProperties: null, responseId, itemId, outputIndex, contentIndex); } - public static ConversationRateLimitsUpdate ConversationRateLimitsUpdate(string eventId = null, IEnumerable allDetails = null) + public static ConversationRateLimitsUpdate ConversationRateLimitsUpdate(string eventId = default, IEnumerable allDetails = default) { - allDetails ??= new List(); + allDetails ??= new ChangeTrackingList(); - return new ConversationRateLimitsUpdate(ConversationUpdateKind.RateLimitsUpdated, eventId, serializedAdditionalRawData: null, allDetails?.ToList()); + return new ConversationRateLimitsUpdate(eventId, RealtimeConversation.ConversationUpdateKind.RateLimitsUpdated, additionalBinaryDataProperties: null, allDetails?.ToList()); } - public static ConversationRateLimitDetailsItem ConversationRateLimitDetailsItem(string name = null, int maximumCount = default, int remainingCount = default, TimeSpan timeUntilReset = default) + public static ConversationRateLimitDetailsItem ConversationRateLimitDetailsItem(string name = default, int maximumCount = default, int remainingCount = default, TimeSpan timeUntilReset = default) { - return new ConversationRateLimitDetailsItem(name, maximumCount, remainingCount, timeUntilReset, serializedAdditionalRawData: null); + + return new ConversationRateLimitDetailsItem(name, maximumCount, remainingCount, timeUntilReset, additionalBinaryDataProperties: null); } - public static ModerationResultCollection ModerationResultCollection(string id = null, string model = null, IEnumerable results = null) + public static ModerationResultCollection ModerationResultCollection(string id = default, string model = default, IEnumerable results = default) { - results ??= new List(); + results ??= new ChangeTrackingList(); return new ModerationResultCollection(id, model, results?.ToList()); } + public static ModerationResult ModerationResult(bool flagged = default) + { + + return new ModerationResult(flagged, additionalBinaryDataProperties: null); + } + + public static OpenAIModelCollection OpenAIModelCollection(InternalListModelsResponseObject @object = default, IEnumerable data = default) + { + data ??= new ChangeTrackingList(); + + return new OpenAIModelCollection(@object, data?.ToList(), serializedAdditionalRawData: null); + } + + public static OpenAIModel OpenAIModel(string id = default, string ownedBy = default, InternalModelObject @object = default, DateTimeOffset createdAt = default) + { + + return new OpenAIModel(id, ownedBy, @object, createdAt, additionalBinaryDataProperties: null); + } + + public static ModelDeletionResult ModelDeletionResult(bool deleted = default, string modelId = default, InternalDeleteModelResponseObject @object = default) + { + + return new ModelDeletionResult(deleted, modelId, @object, additionalBinaryDataProperties: null); + } + + public static ThreadMessage ThreadMessage(string id = default, DateTimeOffset createdAt = default, string threadId = default, MessageStatus status = default, MessageFailureDetails incompleteDetails = default, DateTimeOffset? completedAt = default, DateTimeOffset? incompleteAt = default, IEnumerable content = default, string assistantId = default, string runId = default, IReadOnlyDictionary metadata = default, InternalMessageObjectObject @object = default, Assistants.MessageRole role = default, IEnumerable attachments = default) + { + content ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + attachments ??= new ChangeTrackingList(); + + return new ThreadMessage( + id, + createdAt, + threadId, + status, + incompleteDetails, + completedAt, + incompleteAt, + content?.ToList(), + assistantId, + runId, + metadata, + @object, + role, + attachments?.ToList(), + additionalBinaryDataProperties: null); + } + public static MessageFailureDetails MessageFailureDetails(MessageFailureReason reason = default) { - return new MessageFailureDetails(reason, serializedAdditionalRawData: null); + + return new MessageFailureDetails(reason, additionalBinaryDataProperties: null); + } + + public static MessageModificationOptions MessageModificationOptions(IDictionary metadata = default) + { + metadata ??= new ChangeTrackingDictionary(); + + return new MessageModificationOptions(metadata, additionalBinaryDataProperties: null); + } + + public static MessageDeletionResult MessageDeletionResult(bool deleted = default, string messageId = default, InternalDeleteMessageResponseObject @object = default) + { + + return new MessageDeletionResult(deleted, messageId, @object, additionalBinaryDataProperties: null); + } + + public static ImageGenerationOptions ImageGenerationOptions(GeneratedImageQuality? quality = default, GeneratedImageFormat? responseFormat = default, GeneratedImageSize? size = default, GeneratedImageStyle? style = default, InternalCreateImageRequestModel? model = default, string prompt = default, long? n = default, string endUserId = default) + { + + return new ImageGenerationOptions( + quality, + responseFormat, + size, + style, + model, + prompt, + n, + endUserId, + additionalBinaryDataProperties: null); } - public static GeneratedImageCollection GeneratedImageCollection(DateTimeOffset created = default, IEnumerable data = null) + public static GeneratedImageCollection GeneratedImageCollection(DateTimeOffset created = default, IEnumerable data = default) { - data ??= new List(); + data ??= new ChangeTrackingList(); return new GeneratedImageCollection(created, data?.ToList()); } - public static GeneratedImage GeneratedImage(BinaryData imageBytes = null, Uri imageUri = null, string revisedPrompt = null) + public static GeneratedImage GeneratedImage(string revisedPrompt = default, BinaryData imageBytes = default, Uri imageUri = default) + { + + return new GeneratedImage(revisedPrompt, imageBytes, imageUri, additionalBinaryDataProperties: null); + } + + public static ImageEditOptions ImageEditOptions(InternalCreateImageEditRequestModel? model = default, BinaryData image = default, string prompt = default, BinaryData mask = default, long? n = default, GeneratedImageSize? size = default, GeneratedImageFormat? responseFormat = default, string endUserId = default) + { + + return new ImageEditOptions( + model, + image, + prompt, + mask, + n, + size, + responseFormat, + endUserId, + additionalBinaryDataProperties: null); + } + + public static ImageVariationOptions ImageVariationOptions(InternalCreateImageVariationRequestModel? model = default, BinaryData image = default, long? n = default, GeneratedImageSize? size = default, GeneratedImageFormat? responseFormat = default, string endUserId = default) + { + + return new ImageVariationOptions( + model, + image, + n, + size, + responseFormat, + endUserId, + additionalBinaryDataProperties: null); + } + + public static OpenAIFileCollection OpenAIFileCollection(IEnumerable data = default, InternalListFilesResponseObject @object = default) + { + data ??= new ChangeTrackingList(); + + return new OpenAIFileCollection(data?.ToList(), @object, serializedAdditionalRawData: null); + } + + public static FileDeletionResult FileDeletionResult(bool deleted = default, string fileId = default, InternalDeleteFileResponseObject @object = default) + { + + return new FileDeletionResult(deleted, fileId, @object, additionalBinaryDataProperties: null); + } + + public static EmbeddingGenerationOptions EmbeddingGenerationOptions(int? dimensions = default, BinaryData input = default, InternalCreateEmbeddingRequestModel model = default, InternalCreateEmbeddingRequestEncodingFormat? encodingFormat = default, string endUserId = default) { - return new GeneratedImage(imageBytes, imageUri, revisedPrompt, serializedAdditionalRawData: null); + + return new EmbeddingGenerationOptions( + dimensions, + input, + model, + encodingFormat, + endUserId, + additionalBinaryDataProperties: null); + } + + public static OpenAIEmbeddingCollection OpenAIEmbeddingCollection(IEnumerable data = default, string model = default, InternalCreateEmbeddingResponseObject @object = default, EmbeddingTokenUsage usage = default) + { + data ??= new ChangeTrackingList(); + + return new OpenAIEmbeddingCollection(data?.ToList(), model, @object, usage, serializedAdditionalRawData: null); + } + + public static OpenAIEmbedding OpenAIEmbedding(int index = default, BinaryData embeddingProperty = default, InternalEmbeddingObject @object = default) + { + + return new OpenAIEmbedding(index, embeddingProperty, @object, serializedAdditionalRawData: null); } public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokenCount = default, int totalTokenCount = default) { - return new EmbeddingTokenUsage(inputTokenCount, totalTokenCount, serializedAdditionalRawData: null); + + return new EmbeddingTokenUsage(inputTokenCount, totalTokenCount, additionalBinaryDataProperties: null); } - public static ChatTokenUsage ChatTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default, ChatOutputTokenUsageDetails outputTokenDetails = null, ChatInputTokenUsageDetails inputTokenDetails = null) + public static ChatTokenUsage ChatTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default, ChatOutputTokenUsageDetails outputTokenDetails = default, ChatInputTokenUsageDetails inputTokenDetails = default) { + return new ChatTokenUsage( outputTokenCount, inputTokenCount, totalTokenCount, outputTokenDetails, inputTokenDetails, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); } - public static ChatOutputTokenUsageDetails ChatOutputTokenUsageDetails(int audioTokenCount = default, int reasoningTokenCount = default) + public static ChatOutputTokenUsageDetails ChatOutputTokenUsageDetails(int reasoningTokenCount = default, int audioTokenCount = default) { - return new ChatOutputTokenUsageDetails(audioTokenCount, reasoningTokenCount, serializedAdditionalRawData: null); + + return new ChatOutputTokenUsageDetails(reasoningTokenCount, audioTokenCount, additionalBinaryDataProperties: null); } public static ChatInputTokenUsageDetails ChatInputTokenUsageDetails(int audioTokenCount = default, int cachedTokenCount = default) { - return new ChatInputTokenUsageDetails(audioTokenCount, cachedTokenCount, serializedAdditionalRawData: null); + + return new ChatInputTokenUsageDetails(audioTokenCount, cachedTokenCount, additionalBinaryDataProperties: null); } - public static ChatMessage ChatMessage(ChatMessageContent content = null) + public static ChatCompletionOptions ChatCompletionOptions(float? frequencyPenalty = default, float? presencePenalty = default, ChatResponseFormat responseFormat = default, float? temperature = default, float? topP = default, IEnumerable tools = default, IEnumerable messages = default, InternalCreateChatCompletionRequestModel model = default, int? n = default, bool? stream = default, InternalChatCompletionStreamOptions streamOptions = default, bool? includeLogProbabilities = default, int? topLogProbabilityCount = default, IEnumerable stopSequences = default, IDictionary logitBiases = default, ChatToolChoice toolChoice = default, ChatFunctionChoice functionChoice = default, bool? allowParallelToolCalls = default, string endUserId = default, long? seed = default, int? deprecatedMaxTokens = default, int? maxOutputTokenCount = default, IEnumerable functions = default, IDictionary metadata = default, bool? storedOutputEnabled = default, InternalCreateChatCompletionRequestServiceTier? serviceTier = default) { - return new InternalUnknownChatMessage(default, content, serializedAdditionalRawData: null); + tools ??= new ChangeTrackingList(); + messages ??= new ChangeTrackingList(); + stopSequences ??= new ChangeTrackingList(); + logitBiases ??= new ChangeTrackingDictionary(); + functions ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); + + return new ChatCompletionOptions( + frequencyPenalty, + presencePenalty, + responseFormat, + temperature, + topP, + tools?.ToList(), + messages?.ToList(), + model, + n, + stream, + streamOptions, + includeLogProbabilities, + topLogProbabilityCount, + stopSequences?.ToList(), + logitBiases, + toolChoice, + functionChoice, + allowParallelToolCalls, + endUserId, + seed, + deprecatedMaxTokens, + maxOutputTokenCount, + functions?.ToList(), + metadata, + storedOutputEnabled, + serviceTier, + additionalBinaryDataProperties: null); } - public static SystemChatMessage SystemChatMessage(ChatMessageContent content = null, string participantName = null) + public static ChatMessage ChatMessage(string role = default, ChatMessageContent content = default) { - return new SystemChatMessage(ChatMessageRole.System, content, serializedAdditionalRawData: null, participantName); + + return new InternalUnknownChatMessage(role.ToChatMessageRole(), content, additionalBinaryDataProperties: null); } - public static UserChatMessage UserChatMessage(ChatMessageContent content = null, string participantName = null) + public static SystemChatMessage SystemChatMessage(ChatMessageContent content = default, string participantName = default) { - return new UserChatMessage(ChatMessageRole.User, content, serializedAdditionalRawData: null, participantName); + + return new SystemChatMessage(Chat.ChatMessageRole.System, content, additionalBinaryDataProperties: null, participantName); } - public static AssistantChatMessage AssistantChatMessage(ChatMessageContent content = null, string refusal = null, string participantName = null, IEnumerable toolCalls = null, ChatFunctionCall functionCall = null) + public static UserChatMessage UserChatMessage(ChatMessageContent content = default, string participantName = default) { - toolCalls ??= new List(); + + return new UserChatMessage(Chat.ChatMessageRole.User, content, additionalBinaryDataProperties: null, participantName); + } + + public static AssistantChatMessage AssistantChatMessage(ChatMessageContent content = default, string refusal = default, string participantName = default, IEnumerable toolCalls = default, ChatFunctionCall functionCall = default) + { + toolCalls ??= new ChangeTrackingList(); return new AssistantChatMessage( - ChatMessageRole.Assistant, + Chat.ChatMessageRole.Assistant, content, - serializedAdditionalRawData: null, + additionalBinaryDataProperties: null, refusal, participantName, toolCalls?.ToList(), functionCall); } - public static ToolChatMessage ToolChatMessage(ChatMessageContent content = null, string toolCallId = null) + public static ChatToolCall ChatToolCall(string id = default, InternalChatCompletionMessageToolCallFunction function = default, Chat.ChatToolCallKind kind = default) + { + + return new ChatToolCall(id, function, kind, additionalBinaryDataProperties: null); + } + + public static ChatFunctionCall ChatFunctionCall(string functionName = default, BinaryData functionArguments = default) + { + + return new ChatFunctionCall(functionName, functionArguments, additionalBinaryDataProperties: null); + } + + public static ToolChatMessage ToolChatMessage(ChatMessageContent content = default, string toolCallId = default) + { + + return new ToolChatMessage(Chat.ChatMessageRole.Tool, content, additionalBinaryDataProperties: null, toolCallId); + } + + public static FunctionChatMessage FunctionChatMessage(ChatMessageContent content = default, string functionName = default) + { + + return new FunctionChatMessage(Chat.ChatMessageRole.Function, content, additionalBinaryDataProperties: null, functionName); + } + + public static ChatResponseFormat ChatResponseFormat(string @type = default) + { + + return new InternalUnknownChatResponseFormat(@type, additionalBinaryDataProperties: null); + } + + public static ChatTool ChatTool(InternalFunctionDefinition function = default, Chat.ChatToolKind kind = default) + { + + return new ChatTool(function, kind, additionalBinaryDataProperties: null); + } + + public static ChatFunction ChatFunction(string functionName = default, string functionDescription = default, BinaryData functionParameters = default) { - return new ToolChatMessage(ChatMessageRole.Tool, content, serializedAdditionalRawData: null, toolCallId); + + return new ChatFunction(functionName, functionDescription, functionParameters, additionalBinaryDataProperties: null); + } + + public static ChatCompletion ChatCompletion(string id = default, string model = default, string systemFingerprint = default, ChatTokenUsage usage = default, InternalCreateChatCompletionResponseObject @object = default, InternalCreateChatCompletionResponseServiceTier? serviceTier = default, IEnumerable choices = default, DateTimeOffset createdAt = default) + { + choices ??= new ChangeTrackingList(); + + return new ChatCompletion( + id, + model, + systemFingerprint, + usage, + @object, + serviceTier, + choices?.ToList(), + createdAt, + additionalBinaryDataProperties: null); + } + + public static ChatTokenLogProbabilityDetails ChatTokenLogProbabilityDetails(string token = default, float logProbability = default, ReadOnlyMemory? utf8Bytes = default, IEnumerable topLogProbabilities = default) + { + topLogProbabilities ??= new ChangeTrackingList(); + + return new ChatTokenLogProbabilityDetails(token, logProbability, utf8Bytes, topLogProbabilities?.ToList(), additionalBinaryDataProperties: null); } - public static FunctionChatMessage FunctionChatMessage(ChatMessageContent content = null, string functionName = null) + public static ChatTokenTopLogProbabilityDetails ChatTokenTopLogProbabilityDetails(string token = default, float logProbability = default, ReadOnlyMemory? utf8Bytes = default) { - return new FunctionChatMessage(ChatMessageRole.Function, content, serializedAdditionalRawData: null, functionName); + + return new ChatTokenTopLogProbabilityDetails(token, logProbability, utf8Bytes, additionalBinaryDataProperties: null); } - public static ChatFunction ChatFunction(string functionDescription = null, string functionName = null, BinaryData functionParameters = null) + public static AssistantCreationOptions AssistantCreationOptions(string name = default, string description = default, string instructions = default, IDictionary metadata = default, float? temperature = default, string model = default, IEnumerable tools = default, ToolResources toolResources = default, AssistantResponseFormat responseFormat = default, float? nucleusSamplingFactor = default) { - return new ChatFunction(functionDescription, functionName, functionParameters, serializedAdditionalRawData: null); + metadata ??= new ChangeTrackingDictionary(); + tools ??= new ChangeTrackingList(); + + return new AssistantCreationOptions( + name, + description, + instructions, + metadata, + temperature, + model, + tools?.ToList(), + toolResources, + responseFormat, + nucleusSamplingFactor, + additionalBinaryDataProperties: null); } - public static ChatTokenLogProbabilityDetails ChatTokenLogProbabilityDetails(string token = null, float logProbability = default, ReadOnlyMemory? utf8Bytes = null, IEnumerable topLogProbabilities = null) + public static Assistant Assistant(string id = default, DateTimeOffset createdAt = default, string name = default, string description = default, string model = default, string instructions = default, IEnumerable tools = default, ToolResources toolResources = default, IReadOnlyDictionary metadata = default, float? temperature = default, InternalAssistantObjectObject @object = default, AssistantResponseFormat responseFormat = default, float? nucleusSamplingFactor = default) { - topLogProbabilities ??= new List(); + tools ??= new ChangeTrackingList(); + metadata ??= new ChangeTrackingDictionary(); - return new ChatTokenLogProbabilityDetails(token, logProbability, utf8Bytes, topLogProbabilities?.ToList(), serializedAdditionalRawData: null); + return new Assistant( + id, + createdAt, + name, + description, + model, + instructions, + tools?.ToList(), + toolResources, + metadata, + temperature, + @object, + responseFormat, + nucleusSamplingFactor, + additionalBinaryDataProperties: null); + } + + public static ToolResources ToolResources(CodeInterpreterToolResources codeInterpreter = default, FileSearchToolResources fileSearch = default) + { + + return new ToolResources(codeInterpreter, fileSearch, additionalBinaryDataProperties: null); + } + + public static CodeInterpreterToolResources CodeInterpreterToolResources(IEnumerable fileIds = default) + { + fileIds ??= new ChangeTrackingList(); + + return new CodeInterpreterToolResources(fileIds?.ToList(), additionalBinaryDataProperties: null); + } + + public static AssistantModificationOptions AssistantModificationOptions(string name = default, string description = default, string instructions = default, IDictionary metadata = default, float? temperature = default, string model = default, IEnumerable defaultTools = default, ToolResources toolResources = default, AssistantResponseFormat responseFormat = default, float? nucleusSamplingFactor = default) + { + metadata ??= new ChangeTrackingDictionary(); + defaultTools ??= new ChangeTrackingList(); + + return new AssistantModificationOptions( + name, + description, + instructions, + metadata, + temperature, + model, + defaultTools?.ToList(), + toolResources, + responseFormat, + nucleusSamplingFactor, + additionalBinaryDataProperties: null); + } + + public static AssistantDeletionResult AssistantDeletionResult(bool deleted = default, string assistantId = default, InternalDeleteAssistantResponseObject @object = default) + { + + return new AssistantDeletionResult(deleted, assistantId, @object, additionalBinaryDataProperties: null); + } + + public static SpeechGenerationOptions SpeechGenerationOptions(GeneratedSpeechFormat? responseFormat = default, InternalCreateSpeechRequestModel model = default, string input = default, GeneratedSpeechVoice voice = default, float? speedRatio = default) + { + + return new SpeechGenerationOptions( + responseFormat, + model, + input, + voice, + speedRatio, + additionalBinaryDataProperties: null); + } + + public static AudioTranscriptionOptions AudioTranscriptionOptions(string language = default, string prompt = default, AudioTranscriptionFormat? responseFormat = default, float? temperature = default, BinaryData @file = default, InternalCreateTranscriptionRequestModel model = default, IEnumerable internalTimestampGranularities = default) + { + internalTimestampGranularities ??= new ChangeTrackingList(); + + return new AudioTranscriptionOptions( + language, + prompt, + responseFormat, + temperature, + @file, + model, + internalTimestampGranularities?.ToList(), + additionalBinaryDataProperties: null); } - public static ChatTokenTopLogProbabilityDetails ChatTokenTopLogProbabilityDetails(string token = null, float logProbability = default, ReadOnlyMemory? utf8Bytes = null) + public static AudioTranscription AudioTranscription(string language = default, string text = default, IEnumerable words = default, IEnumerable segments = default, InternalCreateTranscriptionResponseVerboseJsonTask task = default, TimeSpan? duration = default) { - return new ChatTokenTopLogProbabilityDetails(token, logProbability, utf8Bytes, serializedAdditionalRawData: null); + words ??= new ChangeTrackingList(); + segments ??= new ChangeTrackingList(); + + return new AudioTranscription( + language, + text, + words?.ToList(), + segments?.ToList(), + task, + duration, + additionalBinaryDataProperties: null); } - public static TranscribedWord TranscribedWord(string word = null, TimeSpan startTime = default, TimeSpan endTime = default) + public static TranscribedWord TranscribedWord(string word = default, TimeSpan startTime = default, TimeSpan endTime = default) { - return new TranscribedWord(word, startTime, endTime, serializedAdditionalRawData: null); + + return new TranscribedWord(word, startTime, endTime, additionalBinaryDataProperties: null); } - public static TranscribedSegment TranscribedSegment(int id = default, int seekOffset = default, TimeSpan startTime = default, TimeSpan endTime = default, string text = null, ReadOnlyMemory tokenIds = default, float temperature = default, float averageLogProbability = default, float compressionRatio = default, float noSpeechProbability = default) + public static TranscribedSegment TranscribedSegment(int id = default, string text = default, float temperature = default, float compressionRatio = default, TimeSpan startTime = default, TimeSpan endTime = default, int seekOffset = default, ReadOnlyMemory tokenIds = default, float averageLogProbability = default, float noSpeechProbability = default) { + return new TranscribedSegment( id, - seekOffset, + text, + temperature, + compressionRatio, startTime, endTime, - text, + seekOffset, tokenIds, - temperature, averageLogProbability, - compressionRatio, noSpeechProbability, - serializedAdditionalRawData: null); + additionalBinaryDataProperties: null); + } + + public static AudioTranslationOptions AudioTranslationOptions(string prompt = default, AudioTranslationFormat? responseFormat = default, float? temperature = default, BinaryData @file = default, InternalCreateTranslationRequestModel model = default) + { + + return new AudioTranslationOptions( + prompt, + responseFormat, + temperature, + @file, + model, + additionalBinaryDataProperties: null); + } + + public static AudioTranslation AudioTranslation(string language = default, string text = default, IEnumerable segments = default, InternalCreateTranslationResponseVerboseJsonTask task = default, TimeSpan? duration = default) + { + segments ??= new ChangeTrackingList(); + + return new AudioTranslation( + language, + text, + segments?.ToList(), + task, + duration, + additionalBinaryDataProperties: null); } - public static StreamingChatFunctionCallUpdate StreamingChatFunctionCallUpdate(string functionName = null, BinaryData functionArgumentsUpdate = null) + public static AssistantResponseFormat AssistantResponseFormat(string @type = default) { - return new StreamingChatFunctionCallUpdate(functionName, functionArgumentsUpdate, serializedAdditionalRawData: null); + + return new InternalUnknownAssistantResponseFormat(@type, additionalBinaryDataProperties: null); + } + + public static ChatFunctionChoice ChatFunctionChoice(string predefinedFunctionChoice = default) + { + + return new ChatFunctionChoice(predefinedFunctionChoice); + } + + public static ChatToolChoice ChatToolChoice() + { + + return new ChatToolChoice(additionalBinaryDataProperties: null); + } + + public static ChatMessageContent ChatMessageContent() + { + + return new ChatMessageContent(additionalBinaryDataProperties: null); + } + + public static ChatMessageContentPart ChatMessageContentPart(Chat.ChatMessageContentPartKind kind = default, string text = default, InternalChatCompletionRequestMessageContentPartImageImageUrl imageUri = default, string refusal = default) + { + + return new ChatMessageContentPart(kind, text, imageUri, refusal, serializedAdditionalRawData: null); + } + + public static StreamingChatFunctionCallUpdate StreamingChatFunctionCallUpdate(string functionName = default, BinaryData functionArgumentsUpdate = default) + { + + return new StreamingChatFunctionCallUpdate(functionName, functionArgumentsUpdate, additionalBinaryDataProperties: null); + } + + public static StreamingChatToolCallUpdate StreamingChatToolCallUpdate(int index = default, InternalChatCompletionMessageToolCallChunkFunction function = default, Chat.ChatToolCallKind kind = default, string toolCallId = default) + { + + return new StreamingChatToolCallUpdate(index, function, kind, toolCallId, additionalBinaryDataProperties: null); + } + + public static StreamingChatCompletionUpdate StreamingChatCompletionUpdate(string model = default, string systemFingerprint = default, InternalCreateChatCompletionStreamResponseObject @object = default, string completionId = default, InternalCreateChatCompletionStreamResponseServiceTier? serviceTier = default, IEnumerable choices = default, DateTimeOffset createdAt = default, ChatTokenUsage usage = default) + { + choices ??= new ChangeTrackingList(); + + return new StreamingChatCompletionUpdate( + model, + systemFingerprint, + @object, + completionId, + serviceTier, + choices?.ToList(), + createdAt, + usage, + additionalBinaryDataProperties: null); + } + + public static RunStepUpdateCodeInterpreterOutput RunStepUpdateCodeInterpreterOutput(string @type = default) + { + + return new UnknownRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreterOutputsObject(@type, additionalBinaryDataProperties: null); } } } diff --git a/src/Generated/RealtimeConversationClient.RestClient.cs b/src/Generated/RealtimeConversationClient.RestClient.cs new file mode 100644 index 000000000..f00049368 --- /dev/null +++ b/src/Generated/RealtimeConversationClient.RestClient.cs @@ -0,0 +1,15 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; + +namespace OpenAI.RealtimeConversation +{ + public partial class RealtimeConversationClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + } +} diff --git a/src/Generated/RealtimeConversationClient.cs b/src/Generated/RealtimeConversationClient.cs index def54f0ba..6f43538da 100644 --- a/src/Generated/RealtimeConversationClient.cs +++ b/src/Generated/RealtimeConversationClient.cs @@ -5,21 +5,15 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using System.Threading.Tasks; namespace OpenAI.RealtimeConversation { - // Data plane generated sub-client. public partial class RealtimeConversationClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - - public virtual ClientPipeline Pipeline => _pipeline; protected RealtimeConversationClient() { @@ -27,12 +21,11 @@ protected RealtimeConversationClient() internal RealtimeConversationClient(ClientPipeline pipeline, ApiKeyCredential keyCredential, Uri endpoint) { - _pipeline = pipeline; - _keyCredential = keyCredential; _endpoint = endpoint; + Pipeline = pipeline; + _keyCredential = keyCredential; } - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + public ClientPipeline Pipeline { get; } } } diff --git a/src/Generated/VectorStoreClient.RestClient.cs b/src/Generated/VectorStoreClient.RestClient.cs new file mode 100644 index 000000000..322a97d5f --- /dev/null +++ b/src/Generated/VectorStoreClient.RestClient.cs @@ -0,0 +1,123 @@ +// + +#nullable disable + +using System.ClientModel.Primitives; +using OpenAI; + +namespace OpenAI.VectorStores +{ + public partial class VectorStoreClient + { + private static PipelineMessageClassifier _pipelineMessageClassifier200; + + private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 = PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); + + internal PipelineMessage CreateListVectorStoresRequest(int? limit, string order, string after, string before, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListVectorStoreFilesRequest(string vectorStoreId, int? limit, string order, string after, string before, string filter, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + + internal PipelineMessage CreateListFilesInVectorStoreBatchRequest(string vectorStoreId, string batchId, int? limit, string order, string after, string before, string filter, RequestOptions options) + { + PipelineMessage message = Pipeline.CreateMessage(); + message.ResponseClassifier = PipelineMessageClassifier200; + PipelineRequest request = message.Request; + request.Method = "GET"; + ClientUriBuilder uri = new ClientUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/files", false); + if (limit != null) + { + uri.AppendQuery("limit", TypeFormatters.ConvertToString(limit, null), true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + request.Uri = uri.ToUri(); + request.Headers.Set("Accept", "application/json"); + message.Apply(options); + return message; + } + } +} diff --git a/src/Generated/VectorStoreClient.cs b/src/Generated/VectorStoreClient.cs index 520c076aa..975fb140c 100644 --- a/src/Generated/VectorStoreClient.cs +++ b/src/Generated/VectorStoreClient.cs @@ -6,39 +6,37 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Threading.Tasks; +using OpenAI; namespace OpenAI.VectorStores { - // Data plane generated sub-client. public partial class VectorStoreClient { + private readonly Uri _endpoint; private const string AuthorizationHeader = "Authorization"; private readonly ApiKeyCredential _keyCredential; private const string AuthorizationApiKeyPrefix = "Bearer"; - private readonly ClientPipeline _pipeline; - private readonly Uri _endpoint; protected VectorStoreClient() { } - public virtual async Task CreateVectorStoreAsync(BinaryContent content, RequestOptions options = null) + public ClientPipeline Pipeline { get; } + + public virtual ClientResult CreateVectorStore(BinaryContent content, RequestOptions options = null) { Argument.AssertNotNull(content, nameof(content)); - using PipelineMessage message = CreateCreateVectorStoreRequest(content, options); - return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); + using PipelineMessage message = this.CreateCreateVectorStoreRequest(content, options); + return ClientResult.FromResponse(Pipeline.ProcessMessage(message, options)); } - public virtual ClientResult CreateVectorStore(BinaryContent content, RequestOptions options = null) + public virtual async Task CreateVectorStoreAsync(BinaryContent content, RequestOptions options = null) { Argument.AssertNotNull(content, nameof(content)); - using PipelineMessage message = CreateCreateVectorStoreRequest(content, options); - return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options)); + using PipelineMessage message = this.CreateCreateVectorStoreRequest(content, options); + return ClientResult.FromResponse(await Pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false)); } - - private static PipelineMessageClassifier _pipelineMessageClassifier200; - private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 }); } } diff --git a/tests/RealtimeConversation/ConversationSmokeTests.cs b/tests/RealtimeConversation/ConversationSmokeTests.cs index 72bd32522..b405eb97a 100644 --- a/tests/RealtimeConversation/ConversationSmokeTests.cs +++ b/tests/RealtimeConversation/ConversationSmokeTests.cs @@ -27,7 +27,7 @@ public void ToolChoiceSerializationInSessionOptionsWorks() (ConversationToolChoice.CreateNoneToolChoice(), @"{""tool_choice"":""none""}"), (ConversationToolChoice.CreateAutoToolChoice(), @"{""tool_choice"":""auto""}"), (ConversationToolChoice.CreateRequiredToolChoice(), @"{""tool_choice"":""required""}"), - (ConversationToolChoice.CreateFunctionToolChoice("foo"), @"{""function"":{""name"":""foo""}") + (ConversationToolChoice.CreateFunctionToolChoice("foo"), @"""function"":{""name"":""foo""") }) { ConversationSessionOptions options = new() @@ -46,7 +46,7 @@ public void ToolChoiceSerializationInSessionOptionsWorks() Assert.That(mrwToolChoice.Kind, Is.EqualTo(ConversationToolChoiceKind.Unknown)); Assert.That(ModelReaderWriter.Write(mrwToolChoice).ToString(), Does.Contain(@"""type"":""some_manual_type""")); } - + [Test] public void ItemCreation() {