diff --git a/CHANGELOG.md b/CHANGELOG.md index 41277c50..38dc8d05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Release History +## 2.0.0-beta.13 (Unreleased) + +### Features Added + +### Breaking Changes + +- Refactored `ModerationResult` by merging `ModerationCategories` and `ModerationCategoryScores` into individual `ModerationCategory` properties, each with `Flagged` and `Score` properties. (commit_hash) +- Renamed type `OpenAIFileInfo` to `OpenAIFile` and `OpenAIFileInfoCollection` to `OpenAIFileCollection`. (commit_id) +- Renamed type `OpenAIModelInfo` to `OpenAIModel` and `OpenAIModelInfoCollection` to `OpenAIModelCollection`. (commit_id) +- Renamed type `Embedding` to `OpenAIEmbedding` and `EmbeddingCollection` to `OpenAIEmbeddingCollection`. (commit_id) +- Renamed property `ImageUrl` to `ImageUri` and method `FromImageUrl` to `FromImageUri` in `MessageContent`. (commit_id) +- Renamed property `ParallelToolCallsEnabled` to `AllowParallelToolCalls` in `RunCreationOptions`, `ThreadRun`, and `ChatCompletionOptions` types. (commit_id) +- Renamed property `PromptTokens` to `InputTokenCount`, `CompletionTokens` to `OutputTokenCount`, and `TotalTokens` to `TotalTokenCount` in `RunTokenUsage`. (commit_id) +- Renamed property `InputTokens` to `InputTokenCount` and `TotalTokens` to `TotalTokenCount` in `EmbeddingTokenUsage`. (commit_id) + +### Bugs Fixed + +### Other Changes + ## 2.0.0-beta.12 (2024-09-20) ### Features Added diff --git a/api/OpenAI.netstandard2.0.cs b/api/OpenAI.netstandard2.0.cs index 2a4795b8..27ad7145 100644 --- a/api/OpenAI.netstandard2.0.cs +++ b/api/OpenAI.netstandard2.0.cs @@ -447,12 +447,12 @@ public class MessageCollectionOptions { public abstract class MessageContent : IJsonModel, IPersistableModel { public MessageImageDetail? ImageDetail { get; } public string ImageFileId { get; } - public Uri ImageUrl { get; } + public Uri ImageUri { get; } public string Refusal { get; } public string Text { get; } public IReadOnlyList TextAnnotations { get; } public static MessageContent FromImageFileId(string imageFileId, MessageImageDetail? detail = null); - public static MessageContent FromImageUrl(Uri imageUri, MessageImageDetail? detail = null); + public static MessageContent FromImageUri(Uri imageUri, MessageImageDetail? detail = null); public static MessageContent FromText(string text); public static implicit operator MessageContent(string value); MessageContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); @@ -598,13 +598,13 @@ public class RunCollectionOptions { public class RunCreationOptions : IJsonModel, IPersistableModel { public string AdditionalInstructions { get; set; } public IList AdditionalMessages { get; } + public bool? AllowParallelToolCalls { get; set; } public string InstructionsOverride { get; set; } public int? MaxCompletionTokens { get; set; } public int? MaxPromptTokens { get; set; } public IDictionary Metadata { get; } public string ModelOverride { get; set; } public float? NucleusSamplingFactor { get; set; } - public bool? ParallelToolCallsEnabled { get; set; } public AssistantResponseFormat ResponseFormat { get; set; } public float? Temperature { get; set; } public ToolConstraint ToolConstraint { get; set; } @@ -887,9 +887,9 @@ public abstract class RunStepUpdateCodeInterpreterOutput : IJsonModel.Write(ModelReaderWriterOptions options); } public class RunTokenUsage : IJsonModel, IPersistableModel { - public int CompletionTokens { get; } - public int PromptTokens { get; } - public int TotalTokens { get; } + 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); @@ -1011,6 +1011,7 @@ public class ThreadModificationOptions : IJsonModel, BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class ThreadRun : IJsonModel, IPersistableModel { + public bool? AllowParallelToolCalls { get; } public string AssistantId { get; } public DateTimeOffset? CancelledAt { get; } public DateTimeOffset? CompletedAt { get; } @@ -1026,7 +1027,6 @@ public class ThreadRun : IJsonModel, IPersistableModel { public IReadOnlyDictionary Metadata { get; } public string Model { get; } public float? NucleusSamplingFactor { get; } - public bool? ParallelToolCallsEnabled { get; } public IReadOnlyList RequiredActions { get; } public AssistantResponseFormat ResponseFormat { get; } public DateTimeOffset? StartedAt { get; } @@ -1094,7 +1094,7 @@ public class ToolResources : IJsonModel, IPersistableModel, IPersistableModel { public VectorStoreCreationHelper(); - public VectorStoreCreationHelper(IEnumerable files); + public VectorStoreCreationHelper(IEnumerable files); public VectorStoreCreationHelper(IEnumerable fileIds); public FileChunkingStrategy ChunkingStrategy { get; set; } public IList FileIds { get; } @@ -1380,6 +1380,7 @@ public class ChatCompletion : IJsonModel, IPersistableModel, IPersistableModel { + public bool? AllowParallelToolCalls { get; set; } public string EndUserId { get; set; } public float? FrequencyPenalty { get; set; } [Obsolete("This property is obsolete. Please use ToolChoice instead.")] @@ -1389,7 +1390,6 @@ public class ChatCompletionOptions : IJsonModel, IPersist public bool? IncludeLogProbabilities { get; set; } public IDictionary LogitBiases { get; } public int? MaxOutputTokenCount { get; set; } - public bool? ParallelToolCallsEnabled { get; set; } public float? PresencePenalty { get; set; } public ChatResponseFormat ResponseFormat { get; set; } public long? Seed { get; set; } @@ -1747,15 +1747,6 @@ public class UserChatMessage : ChatMessage, IJsonModel, IPersis } } namespace OpenAI.Embeddings { - public class Embedding : IJsonModel, IPersistableModel { - public int Index { get; } - Embedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - Embedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - public ReadOnlyMemory ToFloats(); - } public class EmbeddingClient { protected EmbeddingClient(); protected internal EmbeddingClient(ClientPipeline pipeline, string model, OpenAIClientOptions options); @@ -1764,25 +1755,16 @@ public class EmbeddingClient { public EmbeddingClient(string model, string apiKey, OpenAIClientOptions options); public EmbeddingClient(string model, string apiKey); public virtual ClientPipeline Pipeline { get; } - public virtual ClientResult GenerateEmbedding(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); - public virtual Task> GenerateEmbeddingAsync(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); + public virtual ClientResult GenerateEmbedding(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); + public virtual Task> GenerateEmbeddingAsync(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GenerateEmbeddings(BinaryContent content, RequestOptions options = null); - public virtual ClientResult GenerateEmbeddings(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); - public virtual ClientResult GenerateEmbeddings(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); + public virtual ClientResult GenerateEmbeddings(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); + public virtual ClientResult GenerateEmbeddings(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GenerateEmbeddingsAsync(BinaryContent content, RequestOptions options = null); - public virtual Task> GenerateEmbeddingsAsync(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); - public virtual Task> GenerateEmbeddingsAsync(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); - } - public class EmbeddingCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - public string Model { get; } - public EmbeddingTokenUsage Usage { get; } - EmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - EmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public virtual Task> GenerateEmbeddingsAsync(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); + public virtual Task> GenerateEmbeddingsAsync(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default); } public class EmbeddingGenerationOptions : IJsonModel, IPersistableModel { public int? Dimensions { get; set; } @@ -1794,18 +1776,36 @@ public class EmbeddingGenerationOptions : IJsonModel BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } public class EmbeddingTokenUsage : IJsonModel, IPersistableModel { - public int InputTokens { get; } - public int TotalTokens { get; } + 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 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 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 class OpenAIEmbeddingsModelFactory { - public static Embedding Embedding(int index = 0, IEnumerable vector = null); - public static EmbeddingCollection EmbeddingCollection(IEnumerable items = null, string model = null, EmbeddingTokenUsage usage = null); public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokens = 0, int totalTokens = 0); + public static OpenAIEmbedding OpenAIEmbedding(int index = 0, IEnumerable vector = null); + public static OpenAIEmbeddingCollection OpenAIEmbeddingCollection(IEnumerable items = null, string model = null, EmbeddingTokenUsage usage = null); } } namespace OpenAI.Files { @@ -1839,28 +1839,28 @@ public class FileClient { public virtual Task> DownloadFileAsync(string fileId, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetFile(string fileId, RequestOptions options); - public virtual ClientResult GetFile(string fileId, CancellationToken cancellationToken = default); + public virtual ClientResult GetFile(string fileId, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetFileAsync(string fileId, RequestOptions options); - public virtual Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default); - public virtual ClientResult GetFiles(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default); + public virtual Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default); + public virtual ClientResult GetFiles(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetFiles(string purpose, RequestOptions options); - public virtual ClientResult GetFiles(CancellationToken cancellationToken = default); - public virtual Task> GetFilesAsync(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default); + public virtual ClientResult GetFiles(CancellationToken cancellationToken = default); + public virtual Task> GetFilesAsync(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetFilesAsync(string purpose, RequestOptions options); - public virtual Task> GetFilesAsync(CancellationToken cancellationToken = default); - public virtual ClientResult UploadFile(BinaryData file, string filename, FileUploadPurpose purpose); + public virtual Task> GetFilesAsync(CancellationToken cancellationToken = default); + public virtual ClientResult UploadFile(BinaryData file, string filename, FileUploadPurpose purpose); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult UploadFile(BinaryContent content, string contentType, RequestOptions options = null); - public virtual ClientResult UploadFile(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default); - public virtual ClientResult UploadFile(string filePath, FileUploadPurpose purpose); - public virtual Task> UploadFileAsync(BinaryData file, string filename, FileUploadPurpose purpose); + public virtual ClientResult UploadFile(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default); + public virtual ClientResult UploadFile(string filePath, FileUploadPurpose purpose); + public virtual Task> UploadFileAsync(BinaryData file, string filename, FileUploadPurpose purpose); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task UploadFileAsync(BinaryContent content, string contentType, RequestOptions options = null); - public virtual Task> UploadFileAsync(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default); - public virtual Task> UploadFileAsync(string filePath, FileUploadPurpose purpose); + public virtual Task> UploadFileAsync(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default); + public virtual Task> UploadFileAsync(string filePath, FileUploadPurpose purpose); } public class FileDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } @@ -1889,7 +1889,7 @@ public class FileDeletionResult : IJsonModel, IPersistableMo public static bool operator !=(FileUploadPurpose left, FileUploadPurpose right); public override readonly string ToString(); } - public class OpenAIFileInfo : IJsonModel, IPersistableModel { + public class OpenAIFile : IJsonModel, IPersistableModel { public DateTimeOffset CreatedAt { get; } public string Filename { get; } public string Id { get; } @@ -1899,18 +1899,18 @@ public class OpenAIFileInfo : IJsonModel, IPersistableModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIFileInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - } - public class OpenAIFileInfoCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - OpenAIFileInfoCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIFileInfoCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + 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 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 readonly partial struct OpenAIFilePurpose : IEquatable { private readonly object _dummy; @@ -1935,8 +1935,8 @@ public class OpenAIFileInfoCollection : ObjectModel.ReadOnlyCollection items = null); + public static OpenAIFileCollection OpenAIFileCollection(IEnumerable items = null); + public static OpenAIFile OpenAIFileInfo(string id = null, int? sizeInBytes = null, DateTimeOffset createdAt = default, string filename = null, OpenAIFilePurpose purpose = default, OpenAIFileStatus status = default, string statusDetails = null); } [Obsolete("This struct is obsolete. If this is a fine-tuning training file, it may take some time to process after it has been uploaded. While the file is processing, you can still create a fine-tuning job but it will not start until the file processing has completed.")] public readonly partial struct OpenAIFileStatus : IEquatable { @@ -2132,16 +2132,16 @@ public class ModelClient { public virtual Task> DeleteModelAsync(string model, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetModel(string model, RequestOptions options); - public virtual ClientResult GetModel(string model, CancellationToken cancellationToken = default); + public virtual ClientResult GetModel(string model, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetModelAsync(string model, RequestOptions options); - public virtual Task> GetModelAsync(string model, CancellationToken cancellationToken = default); + public virtual Task> GetModelAsync(string model, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetModels(RequestOptions options); - public virtual ClientResult GetModels(CancellationToken cancellationToken = default); + public virtual ClientResult GetModels(CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetModelsAsync(RequestOptions options); - public virtual Task> GetModelsAsync(CancellationToken cancellationToken = default); + public virtual Task> GetModelsAsync(CancellationToken cancellationToken = default); } public class ModelDeletionResult : IJsonModel, IPersistableModel { public bool Deleted { get; } @@ -2152,65 +2152,33 @@ public class ModelDeletionResult : IJsonModel, IPersistable string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); } - public class OpenAIModelInfo : IJsonModel, IPersistableModel { + public class OpenAIModel : IJsonModel, IPersistableModel { public DateTimeOffset CreatedAt { get; } public string Id { get; } public string OwnedBy { get; } - OpenAIModelInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIModelInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - } - public class OpenAIModelInfoCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - OpenAIModelInfoCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - OpenAIModelInfoCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + 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 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 class OpenAIModelsModelFactory { public static ModelDeletionResult ModelDeletionResult(string modelId = null, bool deleted = false); - public static OpenAIModelInfo OpenAIModelInfo(string id = null, DateTimeOffset createdAt = default, string ownedBy = null); - public static OpenAIModelInfoCollection OpenAIModelInfoCollection(IEnumerable items = null); + public static OpenAIModel OpenAIModel(string id = null, DateTimeOffset createdAt = default, string ownedBy = null); + public static OpenAIModelCollection OpenAIModelCollection(IEnumerable items = null); } } namespace OpenAI.Moderations { - public class ModerationCategories : IJsonModel, IPersistableModel { - public bool Harassment { get; } - public bool HarassmentThreatening { get; } - public bool Hate { get; } - public bool HateThreatening { get; } - public bool SelfHarm { get; } - public bool SelfHarmInstructions { get; } - public bool SelfHarmIntent { get; } - public bool Sexual { get; } - public bool SexualMinors { get; } - public bool Violence { get; } - public bool ViolenceGraphic { get; } - ModerationCategories IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModerationCategories IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - } - public class ModerationCategoryScores : IJsonModel, IPersistableModel { - public float Harassment { get; } - public float HarassmentThreatening { get; } - public float Hate { get; } - public float HateThreatening { get; } - public float SelfHarm { get; } - public float SelfHarmInstructions { get; } - public float SelfHarmIntent { get; } - public float Sexual { get; } - public float SexualMinors { get; } - public float Violence { get; } - public float ViolenceGraphic { get; } - ModerationCategoryScores IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModerationCategoryScores IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); + public class ModerationCategory { + public bool Flagged { get; } + public float Score { get; } } public class ModerationClient { protected ModerationClient(); @@ -2222,37 +2190,45 @@ public class ModerationClient { public virtual ClientPipeline Pipeline { get; } [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult ClassifyText(BinaryContent content, RequestOptions options = null); - public virtual ClientResult ClassifyText(IEnumerable inputs, CancellationToken cancellationToken = default); + public virtual ClientResult ClassifyText(IEnumerable inputs, CancellationToken cancellationToken = default); public virtual ClientResult ClassifyText(string input, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task ClassifyTextAsync(BinaryContent content, RequestOptions options = null); - public virtual Task> ClassifyTextAsync(IEnumerable inputs, CancellationToken cancellationToken = default); + public virtual Task> ClassifyTextAsync(IEnumerable inputs, CancellationToken cancellationToken = default); public virtual Task> ClassifyTextAsync(string input, CancellationToken cancellationToken = default); } - public class ModerationCollection : ObjectModel.ReadOnlyCollection, IJsonModel, IPersistableModel { - public string Id { get; } - public string Model { get; } - ModerationCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options); - ModerationCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options); - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options); - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options); - } public class ModerationResult : IJsonModel, IPersistableModel { - public ModerationCategories Categories { get; } - public ModerationCategoryScores CategoryScores { get; } public bool Flagged { get; } + public ModerationCategory Harassment { get; } + public ModerationCategory HarassmentThreatening { get; } + public ModerationCategory Hate { get; } + public ModerationCategory HateThreatening { get; } + public ModerationCategory SelfHarm { get; } + public ModerationCategory SelfHarmInstructions { get; } + public ModerationCategory SelfHarmIntent { get; } + public ModerationCategory Sexual { get; } + 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 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 class OpenAIModerationsModelFactory { - public static ModerationCategories ModerationCategories(bool hate = false, bool hateThreatening = false, bool harassment = false, bool harassmentThreatening = false, bool selfHarm = false, bool selfHarmIntent = false, bool selfHarmInstructions = false, bool sexual = false, bool sexualMinors = false, bool violence = false, bool violenceGraphic = false); - public static ModerationCategoryScores ModerationCategoryScores(float hate = 0, float hateThreatening = 0, float harassment = 0, float harassmentThreatening = 0, float selfHarm = 0, float selfHarmIntent = 0, float selfHarmInstructions = 0, float sexual = 0, float sexualMinors = 0, float violence = 0, float violenceGraphic = 0); - public static ModerationCollection ModerationCollection(string id = null, string model = null, IEnumerable items = null); - public static ModerationResult ModerationResult(bool flagged = false, ModerationCategories categories = null, ModerationCategoryScores categoryScores = null); + public static ModerationCategory ModerationCategory(bool flagged = false, float score = 0); + public static ModerationResult ModerationResult(bool flagged = false, ModerationCategory hate = null, ModerationCategory hateThreatening = null, ModerationCategory harassment = null, ModerationCategory harassmentThreatening = null, ModerationCategory selfHarm = null, ModerationCategory selfHarmIntent = null, ModerationCategory selfHarmInstructions = null, ModerationCategory sexual = null, ModerationCategory sexualMinors = null, ModerationCategory violence = null, ModerationCategory violenceGraphic = null); + public static ModerationResultCollection ModerationResultCollection(string id = null, string model = null, IEnumerable items = null); } } namespace OpenAI.VectorStores { @@ -2340,11 +2316,11 @@ public class VectorStoreClient { public VectorStoreClient(string apiKey, OpenAIClientOptions options); public VectorStoreClient(string apiKey); public virtual ClientPipeline Pipeline { get; } - public virtual ClientResult AddFileToVectorStore(VectorStore vectorStore, OpenAIFileInfo file); + public virtual ClientResult AddFileToVectorStore(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult AddFileToVectorStore(string vectorStoreId, BinaryContent content, RequestOptions options = null); public virtual ClientResult AddFileToVectorStore(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); - public virtual Task> AddFileToVectorStoreAsync(VectorStore vectorStore, OpenAIFileInfo file); + public virtual Task> AddFileToVectorStoreAsync(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task AddFileToVectorStoreAsync(string vectorStoreId, BinaryContent content, RequestOptions options = null); public virtual Task> AddFileToVectorStoreAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); @@ -2356,11 +2332,11 @@ public class VectorStoreClient { [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task CancelBatchFileJobAsync(string vectorStoreId, string batchId, RequestOptions options); public virtual Task> CancelBatchFileJobAsync(string vectorStoreId, string batchJobId, CancellationToken cancellationToken = default); - public virtual ClientResult CreateBatchFileJob(VectorStore vectorStore, IEnumerable files); + public virtual ClientResult CreateBatchFileJob(VectorStore vectorStore, IEnumerable files); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult CreateBatchFileJob(string vectorStoreId, BinaryContent content, RequestOptions options = null); public virtual ClientResult CreateBatchFileJob(string vectorStoreId, IEnumerable fileIds, CancellationToken cancellationToken = default); - public virtual Task> CreateBatchFileJobAsync(VectorStore vectorStore, IEnumerable files); + public virtual Task> CreateBatchFileJobAsync(VectorStore vectorStore, IEnumerable files); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task CreateBatchFileJobAsync(string vectorStoreId, BinaryContent content, RequestOptions options = null); public virtual Task> CreateBatchFileJobAsync(string vectorStoreId, IEnumerable fileIds, CancellationToken cancellationToken = default); @@ -2385,11 +2361,11 @@ public class VectorStoreClient { [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetBatchFileJobAsync(string vectorStoreId, string batchId, RequestOptions options); public virtual Task> GetBatchFileJobAsync(string vectorStoreId, string batchJobId, CancellationToken cancellationToken = default); - public virtual ClientResult GetFileAssociation(VectorStore vectorStore, OpenAIFileInfo file); + public virtual ClientResult GetFileAssociation(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult GetFileAssociation(string vectorStoreId, string fileId, RequestOptions options); public virtual ClientResult GetFileAssociation(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); - public virtual Task> GetFileAssociationAsync(VectorStore vectorStore, OpenAIFileInfo file); + public virtual Task> GetFileAssociationAsync(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task GetFileAssociationAsync(string vectorStoreId, string fileId, RequestOptions options); public virtual Task> GetFileAssociationAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); @@ -2437,11 +2413,11 @@ public class VectorStoreClient { public virtual Task> ModifyVectorStoreAsync(string vectorStoreId, VectorStoreModificationOptions vectorStore, CancellationToken cancellationToken = default); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task ModifyVectorStoreAsync(string vectorStoreId, BinaryContent content, RequestOptions options = null); - public virtual ClientResult RemoveFileFromStore(VectorStore vectorStore, OpenAIFileInfo file); + public virtual ClientResult RemoveFileFromStore(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual ClientResult RemoveFileFromStore(string vectorStoreId, string fileId, RequestOptions options); public virtual ClientResult RemoveFileFromStore(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); - public virtual Task> RemoveFileFromStoreAsync(VectorStore vectorStore, OpenAIFileInfo file); + public virtual Task> RemoveFileFromStoreAsync(VectorStore vectorStore, OpenAIFile file); [EditorBrowsable(EditorBrowsableState.Never)] public virtual Task RemoveFileFromStoreAsync(string vectorStoreId, string fileId, RequestOptions options); public virtual Task> RemoveFileFromStoreAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); diff --git a/examples/Assistants/Example01_RetrievalAugmentedGeneration.cs b/examples/Assistants/Example01_RetrievalAugmentedGeneration.cs index 4e4a6038..148ef0e5 100644 --- a/examples/Assistants/Example01_RetrievalAugmentedGeneration.cs +++ b/examples/Assistants/Example01_RetrievalAugmentedGeneration.cs @@ -49,7 +49,7 @@ public void Example01_RetrievalAugmentedGeneration() } """).ToStream(); - OpenAIFileInfo salesFile = fileClient.UploadFile( + OpenAIFile salesFile = fileClient.UploadFile( document, "monthly_sales.json", FileUploadPurpose.Assistants); @@ -129,7 +129,7 @@ CollectionResult messages } if (!string.IsNullOrEmpty(contentItem.ImageFileId)) { - OpenAIFileInfo imageInfo = fileClient.GetFile(contentItem.ImageFileId); + OpenAIFile imageInfo = fileClient.GetFile(contentItem.ImageFileId); BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId); using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png"); imageBytes.ToStream().CopyTo(stream); diff --git a/examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs b/examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs index 319e9017..ec6b3368 100644 --- a/examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs +++ b/examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs @@ -50,7 +50,7 @@ public async Task Example01_RetrievalAugmentedGenerationAsync() } """).ToStream(); - OpenAIFileInfo salesFile = await fileClient.UploadFileAsync( + OpenAIFile salesFile = await fileClient.UploadFileAsync( document, "monthly_sales.json", FileUploadPurpose.Assistants); @@ -130,7 +130,7 @@ AsyncCollectionResult messages } if (!string.IsNullOrEmpty(contentItem.ImageFileId)) { - OpenAIFileInfo imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId); + OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId); BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId); using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png"); imageBytes.ToStream().CopyTo(stream); diff --git a/examples/Assistants/Example04_AllTheTools.cs b/examples/Assistants/Example04_AllTheTools.cs index 683e2d11..62b76a43 100644 --- a/examples/Assistants/Example04_AllTheTools.cs +++ b/examples/Assistants/Example04_AllTheTools.cs @@ -44,7 +44,7 @@ static string GetNameOfFamilyMember(string relation) #region Upload a mock file for use with file search FileClient fileClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - OpenAIFileInfo favoriteNumberFile = fileClient.UploadFile( + OpenAIFile favoriteNumberFile = fileClient.UploadFile( BinaryData.FromString(""" This file contains the favorite numbers for individuals. diff --git a/examples/Assistants/Example05_AssistantsWithVision.cs b/examples/Assistants/Example05_AssistantsWithVision.cs index d7af0620..94460187 100644 --- a/examples/Assistants/Example05_AssistantsWithVision.cs +++ b/examples/Assistants/Example05_AssistantsWithVision.cs @@ -16,7 +16,7 @@ public void Example05_AssistantsWithVision() FileClient fileClient = openAIClient.GetFileClient(); AssistantClient assistantClient = openAIClient.GetAssistantClient(); - OpenAIFileInfo pictureOfAppleFile = fileClient.UploadFile( + OpenAIFile pictureOfAppleFile = fileClient.UploadFile( "picture-of-apple.jpg", FileUploadPurpose.Vision); Uri linkToPictureOfOrange = new("https://platform.openai.com/fictitious-files/picture-of-orange.png"); @@ -38,7 +38,7 @@ public void Example05_AssistantsWithVision() [ "Hello, assistant! Please compare these two images for me:", MessageContent.FromImageFileId(pictureOfAppleFile.Id), - MessageContent.FromImageUrl(linkToPictureOfOrange), + MessageContent.FromImageUri(linkToPictureOfOrange), ]), } }); diff --git a/examples/Assistants/Example05_AssistantsWithVisionAsync.cs b/examples/Assistants/Example05_AssistantsWithVisionAsync.cs index 1e1e521f..97443aad 100644 --- a/examples/Assistants/Example05_AssistantsWithVisionAsync.cs +++ b/examples/Assistants/Example05_AssistantsWithVisionAsync.cs @@ -17,7 +17,7 @@ public async Task Example05_AssistantsWithVisionAsync() FileClient fileClient = openAIClient.GetFileClient(); AssistantClient assistantClient = openAIClient.GetAssistantClient(); - OpenAIFileInfo pictureOfAppleFile = await fileClient.UploadFileAsync( + OpenAIFile pictureOfAppleFile = await fileClient.UploadFileAsync( "picture-of-apple.jpg", FileUploadPurpose.Vision); Uri linkToPictureOfOrange = new("https://platform.openai.com/fictitious-files/picture-of-orange.png"); @@ -39,7 +39,7 @@ public async Task Example05_AssistantsWithVisionAsync() [ "Hello, assistant! Please compare these two images for me:", MessageContent.FromImageFileId(pictureOfAppleFile.Id), - MessageContent.FromImageUrl(linkToPictureOfOrange), + MessageContent.FromImageUri(linkToPictureOfOrange), ]), } }); diff --git a/examples/Embeddings/Example01_SimpleEmbedding.cs b/examples/Embeddings/Example01_SimpleEmbedding.cs index f9170521..163d2f53 100644 --- a/examples/Embeddings/Example01_SimpleEmbedding.cs +++ b/examples/Embeddings/Example01_SimpleEmbedding.cs @@ -15,7 +15,7 @@ public void Example01_SimpleEmbedding() + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" + " attractions. We highly recommend this hotel."; - Embedding embedding = client.GenerateEmbedding(description); + OpenAIEmbedding embedding = client.GenerateEmbedding(description); ReadOnlyMemory vector = embedding.ToFloats(); Console.WriteLine($"Dimension: {vector.Length}"); diff --git a/examples/Embeddings/Example01_SimpleEmbeddingAsync.cs b/examples/Embeddings/Example01_SimpleEmbeddingAsync.cs index fb62f912..19061850 100644 --- a/examples/Embeddings/Example01_SimpleEmbeddingAsync.cs +++ b/examples/Embeddings/Example01_SimpleEmbeddingAsync.cs @@ -16,7 +16,7 @@ public async Task Example01_SimpleEmbeddingAsync() + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" + " attractions. We highly recommend this hotel."; - Embedding embedding = await client.GenerateEmbeddingAsync(description); + OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description); ReadOnlyMemory vector = embedding.ToFloats(); Console.WriteLine($"Dimension: {vector.Length}"); diff --git a/examples/Embeddings/Example02_EmbeddingWithOptions.cs b/examples/Embeddings/Example02_EmbeddingWithOptions.cs index 27859f81..56f3af14 100644 --- a/examples/Embeddings/Example02_EmbeddingWithOptions.cs +++ b/examples/Embeddings/Example02_EmbeddingWithOptions.cs @@ -17,7 +17,7 @@ public void Example02_EmbeddingWithOptions() EmbeddingGenerationOptions options = new() { Dimensions = 512 }; - Embedding embedding = client.GenerateEmbedding(description, options); + OpenAIEmbedding embedding = client.GenerateEmbedding(description, options); ReadOnlyMemory vector = embedding.ToFloats(); Console.WriteLine($"Dimension: {vector.Length}"); diff --git a/examples/Embeddings/Example02_EmbeddingWithOptionsAsync.cs b/examples/Embeddings/Example02_EmbeddingWithOptionsAsync.cs index 53673d66..4c359dde 100644 --- a/examples/Embeddings/Example02_EmbeddingWithOptionsAsync.cs +++ b/examples/Embeddings/Example02_EmbeddingWithOptionsAsync.cs @@ -18,7 +18,7 @@ public async Task Example02_EmbeddingWithOptionsAsync() EmbeddingGenerationOptions options = new() { Dimensions = 512 }; - Embedding embedding = await client.GenerateEmbeddingAsync(description, options); + OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description, options); ReadOnlyMemory vector = embedding.ToFloats(); Console.WriteLine($"Dimension: {vector.Length}"); diff --git a/examples/Embeddings/Example03_MultipleEmbeddings.cs b/examples/Embeddings/Example03_MultipleEmbeddings.cs index fd04f4e5..1e3a854f 100644 --- a/examples/Embeddings/Example03_MultipleEmbeddings.cs +++ b/examples/Embeddings/Example03_MultipleEmbeddings.cs @@ -18,9 +18,9 @@ public void Example03_MultipleEmbeddings() + " attractions. We highly recommend this hotel."; List inputs = [category, description]; - EmbeddingCollection collection = client.GenerateEmbeddings(inputs); + OpenAIEmbeddingCollection collection = client.GenerateEmbeddings(inputs); - foreach (Embedding embedding in collection) + foreach (OpenAIEmbedding embedding in collection) { ReadOnlyMemory vector = embedding.ToFloats(); diff --git a/examples/Embeddings/Example03_MultipleEmbeddingsAsync.cs b/examples/Embeddings/Example03_MultipleEmbeddingsAsync.cs index 3cd16671..51cbb030 100644 --- a/examples/Embeddings/Example03_MultipleEmbeddingsAsync.cs +++ b/examples/Embeddings/Example03_MultipleEmbeddingsAsync.cs @@ -19,9 +19,9 @@ public async Task Example03_MultipleEmbeddingsAsync() + " attractions. We highly recommend this hotel."; List inputs = [category, description]; - EmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs); + OpenAIEmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs); - foreach (Embedding embedding in collection) + foreach (OpenAIEmbedding embedding in collection) { ReadOnlyMemory vector = embedding.ToFloats(); diff --git a/src/Custom/Assistants/AssistantClient.cs b/src/Custom/Assistants/AssistantClient.cs index 34416b96..11854de6 100644 --- a/src/Custom/Assistants/AssistantClient.cs +++ b/src/Custom/Assistants/AssistantClient.cs @@ -1267,7 +1267,7 @@ private static BinaryContent CreateThreadAndRunProtocolContent( runOptions.MaxCompletionTokens, runOptions.TruncationStrategy, runOptions.ToolConstraint, - runOptions.ParallelToolCallsEnabled, + runOptions.AllowParallelToolCalls, runOptions.ResponseFormat, serializedAdditionalRawData: null); return internalRequest.ToBinaryContent(); diff --git a/src/Custom/Assistants/GeneratorStubs.cs b/src/Custom/Assistants/GeneratorStubs.cs index 93223b65..a384ae6d 100644 --- a/src/Custom/Assistants/GeneratorStubs.cs +++ b/src/Custom/Assistants/GeneratorStubs.cs @@ -22,10 +22,6 @@ public partial class MessageFailureDetails { } [CodeGenModel("MessageObjectIncompleteDetailsReason")] public readonly partial struct MessageFailureReason { } -[Experimental("OPENAI001")] -[CodeGenModel("RunCompletionUsage")] -public partial class RunTokenUsage { } - [Experimental("OPENAI001")] [CodeGenModel("RunObjectLastError")] public partial class RunError { } diff --git a/src/Custom/Assistants/MessageContent.cs b/src/Custom/Assistants/MessageContent.cs index f8b9840e..ff21c52c 100644 --- a/src/Custom/Assistants/MessageContent.cs +++ b/src/Custom/Assistants/MessageContent.cs @@ -26,7 +26,7 @@ public static MessageContent FromImageFileId( /// /// /// - public static MessageContent FromImageUrl(Uri imageUri, MessageImageDetail? detail = null) + public static MessageContent FromImageUri(Uri imageUri, MessageImageDetail? detail = null) => new InternalMessageImageUrlContent(imageUri, detail); /// @@ -38,7 +38,7 @@ public static MessageContent FromText(string text) => new InternalRequestMessageTextContent(text); /// - public Uri ImageUrl => AsInternalImageUrl?.InternalUrl; + public Uri ImageUri => AsInternalImageUrl?.InternalUrl; /// public string ImageFileId => AsInternalImageFile?.InternalFileId; /// diff --git a/src/Custom/Assistants/RunCreationOptions.cs b/src/Custom/Assistants/RunCreationOptions.cs index f4d242f2..dacf4602 100644 --- a/src/Custom/Assistants/RunCreationOptions.cs +++ b/src/Custom/Assistants/RunCreationOptions.cs @@ -75,7 +75,7 @@ private set /// Assumed true if not otherwise specified. /// [CodeGenMember("ParallelToolCalls")] - public bool? ParallelToolCallsEnabled { get; set; } + public bool? AllowParallelToolCalls { get; set; } /// /// A run-specific collection of tool definitions that will override the assistant-level defaults. If not provided, diff --git a/src/Custom/Assistants/RunTokenUsage.cs b/src/Custom/Assistants/RunTokenUsage.cs new file mode 100644 index 00000000..9bfc6e9e --- /dev/null +++ b/src/Custom/Assistants/RunTokenUsage.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace OpenAI.Assistants +{ + [Experimental("OPENAI001")] + [CodeGenModel("RunCompletionUsage")] + public partial class RunTokenUsage + { + // CUSTOM: Renamed. + [CodeGenMember("CompletionTokens")] + public int OutputTokenCount { get; } + + // CUSTOM: Renamed. + [CodeGenMember("PromptTokens")] + public int InputTokenCount { get; } + + // CUSTOM: Renamed. + [CodeGenMember("TotalTokens")] + public int TotalTokenCount { get; } + } +} diff --git a/src/Custom/Assistants/ThreadRun.cs b/src/Custom/Assistants/ThreadRun.cs index 1eb62ecc..f3cbd61e 100644 --- a/src/Custom/Assistants/ThreadRun.cs +++ b/src/Custom/Assistants/ThreadRun.cs @@ -23,7 +23,7 @@ public partial class ThreadRun internal readonly InternalRunRequiredAction _internalRequiredAction; // CUSTOM: Removed null check for `toolConstraint` and `responseFormat`. - internal ThreadRun(string id, 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, IEnumerable tools, IReadOnlyDictionary metadata, RunTokenUsage usage, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? parallelToolCallsEnabled, AssistantResponseFormat responseFormat) + internal ThreadRun(string id, 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, IEnumerable tools, IReadOnlyDictionary metadata, RunTokenUsage usage, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(threadId, nameof(threadId)); @@ -54,7 +54,7 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string MaxCompletionTokens = maxCompletionTokens; TruncationStrategy = truncationStrategy; ToolConstraint = toolConstraint; - ParallelToolCallsEnabled = parallelToolCallsEnabled; + AllowParallelToolCalls = allowParallelToolCalls; ResponseFormat = responseFormat; } @@ -93,6 +93,6 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string /// Assumed true if not otherwise specified. /// [CodeGenMember("ParallelToolCalls")] - public bool? ParallelToolCallsEnabled { get; } + public bool? AllowParallelToolCalls { get; } } diff --git a/src/Custom/Assistants/VectorStoreCreationHelper.cs b/src/Custom/Assistants/VectorStoreCreationHelper.cs index 5a8d84cd..ebba2b8d 100644 --- a/src/Custom/Assistants/VectorStoreCreationHelper.cs +++ b/src/Custom/Assistants/VectorStoreCreationHelper.cs @@ -19,7 +19,7 @@ public VectorStoreCreationHelper(IEnumerable fileIds) Metadata = new ChangeTrackingDictionary(); } - public VectorStoreCreationHelper(IEnumerable files) + public VectorStoreCreationHelper(IEnumerable files) : this(files?.Select(file => file.Id) ?? []) { } } diff --git a/src/Custom/Chat/ChatCompletionOptions.cs b/src/Custom/Chat/ChatCompletionOptions.cs index 5f3a2206..dfbbbba8 100644 --- a/src/Custom/Chat/ChatCompletionOptions.cs +++ b/src/Custom/Chat/ChatCompletionOptions.cs @@ -111,7 +111,7 @@ public ChatCompletionOptions() /// Assumed true if not otherwise specified. /// [CodeGenMember("ParallelToolCalls")] - public bool? ParallelToolCallsEnabled { get; set; } + public bool? AllowParallelToolCalls { get; set; } /// /// An object specifying the format that the model must output. diff --git a/src/Custom/Embeddings/EmbeddingClient.cs b/src/Custom/Embeddings/EmbeddingClient.cs index d10c4a56..ceacabec 100644 --- a/src/Custom/Embeddings/EmbeddingClient.cs +++ b/src/Custom/Embeddings/EmbeddingClient.cs @@ -105,7 +105,7 @@ protected internal EmbeddingClient(ClientPipeline pipeline, string model, OpenAI /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> GenerateEmbeddingAsync(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual async Task> GenerateEmbeddingAsync(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(input, nameof(input)); @@ -114,7 +114,7 @@ public virtual async Task> GenerateEmbeddingAsync(string using BinaryContent content = options.ToBinaryContent(); ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); } // CUSTOM: Added to simplify generating a single embedding from a string input. @@ -124,7 +124,7 @@ public virtual async Task> GenerateEmbeddingAsync(string /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult GenerateEmbedding(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual ClientResult GenerateEmbedding(string input, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(input, nameof(input)); @@ -133,7 +133,7 @@ public virtual ClientResult GenerateEmbedding(string input, Embedding using BinaryContent content = options.ToBinaryContent(); ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of strings instead of BinaryData. @@ -143,7 +143,7 @@ public virtual ClientResult GenerateEmbedding(string input, Embedding /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual async Task> GenerateEmbeddingsAsync(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual async Task> GenerateEmbeddingsAsync(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -152,7 +152,7 @@ public virtual async Task> GenerateEmbeddingsA using BinaryContent content = options.ToBinaryContent(); ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } @@ -163,7 +163,7 @@ public virtual async Task> GenerateEmbeddingsA /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual ClientResult GenerateEmbeddings(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual ClientResult GenerateEmbeddings(IEnumerable inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -172,7 +172,7 @@ public virtual ClientResult GenerateEmbeddings(IEnumerable< using BinaryContent content = options.ToBinaryContent(); ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of a collection of tokens instead of BinaryData. @@ -182,7 +182,7 @@ public virtual ClientResult GenerateEmbeddings(IEnumerable< /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual async Task> GenerateEmbeddingsAsync(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual async Task> GenerateEmbeddingsAsync(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -191,7 +191,7 @@ public virtual async Task> GenerateEmbeddingsA using BinaryContent content = options.ToBinaryContent(); ClientResult result = await GenerateEmbeddingsAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } // CUSTOM: Added to simplify passing the input as a collection of a collection of tokens instead of BinaryData. @@ -201,7 +201,7 @@ public virtual async Task> GenerateEmbeddingsA /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual ClientResult GenerateEmbeddings(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) + public virtual ClientResult GenerateEmbeddings(IEnumerable> inputs, EmbeddingGenerationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -210,7 +210,7 @@ public virtual ClientResult GenerateEmbeddings(IEnumerable< using BinaryContent content = options.ToBinaryContent(); ClientResult result = GenerateEmbeddings(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(EmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIEmbeddingCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } private void CreateEmbeddingGenerationOptions(BinaryData input, ref EmbeddingGenerationOptions options) diff --git a/src/Custom/Embeddings/EmbeddingTokenUsage.cs b/src/Custom/Embeddings/EmbeddingTokenUsage.cs index 54927ecd..cdf1d8a4 100644 --- a/src/Custom/Embeddings/EmbeddingTokenUsage.cs +++ b/src/Custom/Embeddings/EmbeddingTokenUsage.cs @@ -6,5 +6,9 @@ public partial class EmbeddingTokenUsage // CUSTOM: Renamed. /// The number of tokens used by the input prompts. [CodeGenMember("PromptTokens")] - public int InputTokens { get; } + public int InputTokenCount { get; } + + // CUSTOM: Renamed. + [CodeGenMember("TotalTokens")] + public int TotalTokenCount { get; } } \ No newline at end of file diff --git a/src/Custom/Embeddings/Embedding.cs b/src/Custom/Embeddings/OpenAIEmbedding.cs similarity index 91% rename from src/Custom/Embeddings/Embedding.cs rename to src/Custom/Embeddings/OpenAIEmbedding.cs index edc83ee7..949a48f5 100644 --- a/src/Custom/Embeddings/Embedding.cs +++ b/src/Custom/Embeddings/OpenAIEmbedding.cs @@ -11,8 +11,8 @@ namespace OpenAI.Embeddings; /// Represents an embedding vector returned by embedding endpoint. /// [CodeGenModel("Embedding")] -[CodeGenSuppress("Embedding", typeof(int), typeof(BinaryData))] -public partial class Embedding +[CodeGenSuppress("OpenAIEmbedding", typeof(int), typeof(BinaryData))] +public partial class OpenAIEmbedding { // CUSTOM: Made private. The value of the embedding is publicly exposed as ReadOnlyMemory instead of BinaryData. /// @@ -57,6 +57,7 @@ public partial class Embedding /// /// /// + [CodeGenMember("Embedding")] private BinaryData EmbeddingProperty { get; } // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. @@ -64,7 +65,7 @@ public partial class Embedding private InternalEmbeddingObject Object { get; } = InternalEmbeddingObject.Embedding; // CUSTOM: Added logic to handle additional custom properties. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The index of the embedding in the list of embeddings. /// /// The embedding vector, which is a list of floats. The length of vector depends on the model as @@ -72,7 +73,7 @@ public partial class Embedding /// /// The object type, which is always "embedding". /// Keeps track of any properties unknown to the library. - internal Embedding(int index, BinaryData embeddingProperty, InternalEmbeddingObject @object, IDictionary serializedAdditionalRawData) + internal OpenAIEmbedding(int index, BinaryData embeddingProperty, InternalEmbeddingObject @object, IDictionary serializedAdditionalRawData) { Index = index; EmbeddingProperty = embeddingProperty; @@ -84,10 +85,10 @@ internal Embedding(int index, BinaryData embeddingProperty, InternalEmbeddingObj } // CUSTOM: Entirely custom constructor used by the Model Factory. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The index of the embedding in the list of embeddings. /// The embedding vector, which is a list of floats. - internal Embedding(int index, ReadOnlyMemory vector) + internal OpenAIEmbedding(int index, ReadOnlyMemory vector) { Index = index; _vector = vector; diff --git a/src/Custom/Embeddings/EmbeddingCollection.Serialization.cs b/src/Custom/Embeddings/OpenAIEmbeddingCollection.Serialization.cs similarity index 72% rename from src/Custom/Embeddings/EmbeddingCollection.Serialization.cs rename to src/Custom/Embeddings/OpenAIEmbeddingCollection.Serialization.cs index 7bafe4a7..dd25cd2a 100644 --- a/src/Custom/Embeddings/EmbeddingCollection.Serialization.cs +++ b/src/Custom/Embeddings/OpenAIEmbeddingCollection.Serialization.cs @@ -5,23 +5,23 @@ namespace OpenAI.Embeddings; -[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] -public partial class EmbeddingCollection : IJsonModel +[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] +public partial class OpenAIEmbeddingCollection : IJsonModel { // CUSTOM: // - Serialized the Items property. // - Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - => CustomSerializationHelpers.SerializeInstance(this, SerializeEmbeddingCollection, writer, options); + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeOpenAIEmbeddingCollection, writer, options); - internal static void SerializeEmbeddingCollection(EmbeddingCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + internal static void SerializeOpenAIEmbeddingCollection(OpenAIEmbeddingCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); writer.WritePropertyName("data"u8); writer.WriteStartArray(); foreach (var item in instance.Items) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); writer.WritePropertyName("model"u8); @@ -35,7 +35,7 @@ internal static void SerializeEmbeddingCollection(EmbeddingCollection instance, } // CUSTOM: Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - internal static EmbeddingCollection DeserializeEmbeddingCollection(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIEmbeddingCollection DeserializeOpenAIEmbeddingCollection(JsonElement element, ModelReaderWriterOptions options = null) { options ??= new ModelReaderWriterOptions("W"); @@ -43,7 +43,7 @@ internal static EmbeddingCollection DeserializeEmbeddingCollection(JsonElement e { return null; } - IReadOnlyList data = default; + IReadOnlyList data = default; string model = default; InternalCreateEmbeddingResponseObject @object = default; EmbeddingTokenUsage usage = default; @@ -53,10 +53,10 @@ internal static EmbeddingCollection DeserializeEmbeddingCollection(JsonElement e { if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(Embedding.DeserializeEmbedding(item, options)); + array.Add(OpenAIEmbedding.DeserializeOpenAIEmbedding(item, options)); } data = array; continue; @@ -82,6 +82,6 @@ internal static EmbeddingCollection DeserializeEmbeddingCollection(JsonElement e } } serializedAdditionalRawData = rawDataDictionary; - return new EmbeddingCollection(data, model, @object, usage, serializedAdditionalRawData); + return new OpenAIEmbeddingCollection(data, model, @object, usage, serializedAdditionalRawData); } } diff --git a/src/Custom/Embeddings/EmbeddingCollection.cs b/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs similarity index 77% rename from src/Custom/Embeddings/EmbeddingCollection.cs rename to src/Custom/Embeddings/OpenAIEmbeddingCollection.cs index 7fe4ff17..d6797d3a 100644 --- a/src/Custom/Embeddings/EmbeddingCollection.cs +++ b/src/Custom/Embeddings/OpenAIEmbeddingCollection.cs @@ -6,9 +6,9 @@ namespace OpenAI.Embeddings; [CodeGenModel("CreateEmbeddingResponse")] [CodeGenSuppress("Data")] -[CodeGenSuppress(nameof(EmbeddingCollection))] -[CodeGenSuppress(nameof(EmbeddingCollection), typeof(IReadOnlyList), typeof(string), typeof(InternalCreateEmbeddingResponseObject), typeof(EmbeddingTokenUsage))] -public partial class EmbeddingCollection : ReadOnlyCollection +[CodeGenSuppress(nameof(OpenAIEmbeddingCollection))] +[CodeGenSuppress(nameof(OpenAIEmbeddingCollection), typeof(IReadOnlyList), typeof(string), typeof(InternalCreateEmbeddingResponseObject), typeof(EmbeddingTokenUsage))] +public partial class OpenAIEmbeddingCollection : ReadOnlyCollection { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// The object type, which is always "list". @@ -49,12 +49,12 @@ public partial class EmbeddingCollection : ReadOnlyCollection 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 . + /// Initializes a new instance of . /// The list of embeddings generated by the model. /// The name of the model used to generate the embedding. /// The usage information for the request. /// , or is null. - internal EmbeddingCollection(IEnumerable data, string model, EmbeddingTokenUsage usage) + internal OpenAIEmbeddingCollection(IEnumerable data, string model, EmbeddingTokenUsage usage) : base([.. data]) { Argument.AssertNotNull(data, nameof(data)); @@ -66,13 +66,13 @@ internal EmbeddingCollection(IEnumerable data, string model, Embeddin } // CUSTOM: Set the inherited Items property via the base constructor in favor of the suppressed Data property. - /// Initializes a new instance of . + /// Initializes a new instance of . /// The list of embeddings generated by the model. /// The name of the model used to generate the embedding. /// The object type, which is always "list". /// The usage information for the request. /// Keeps track of any properties unknown to the library. - internal EmbeddingCollection(IReadOnlyList data, string model, InternalCreateEmbeddingResponseObject @object, EmbeddingTokenUsage usage, IDictionary serializedAdditionalRawData) + internal OpenAIEmbeddingCollection(IReadOnlyList data, string model, InternalCreateEmbeddingResponseObject @object, EmbeddingTokenUsage usage, IDictionary serializedAdditionalRawData) : base([.. data]) { Model = model; @@ -82,8 +82,8 @@ internal EmbeddingCollection(IReadOnlyList data, string model, Intern } // CUSTOM: Set the inherited Items property via the base constructor in favor of the suppressed Data property. - /// Initializes a new instance of for deserialization. - internal EmbeddingCollection() + /// Initializes a new instance of for deserialization. + internal OpenAIEmbeddingCollection() : base([]) { } diff --git a/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs b/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs index c2b94109..0ab64eac 100644 --- a/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs +++ b/src/Custom/Embeddings/OpenAIEmbeddingsModelFactory.cs @@ -6,24 +6,24 @@ namespace OpenAI.Embeddings; /// Model factory for models. public static partial class OpenAIEmbeddingsModelFactory { - /// Initializes a new instance of . + /// Initializes a new instance of . /// A new instance for mocking. - public static Embedding Embedding(int index = default, IEnumerable vector = null) + public static OpenAIEmbedding OpenAIEmbedding(int index = default, IEnumerable vector = null) { vector ??= new List(); - return new Embedding( + return new OpenAIEmbedding( index, vector.ToArray()); } - /// Initializes a new instance of . - /// A new instance for mocking. - public static EmbeddingCollection EmbeddingCollection(IEnumerable items = null, string model = null, EmbeddingTokenUsage usage = null) + /// Initializes a new instance of . + /// A new instance for mocking. + public static OpenAIEmbeddingCollection OpenAIEmbeddingCollection(IEnumerable items = null, string model = null, EmbeddingTokenUsage usage = null) { - items ??= new List(); + items ??= new List(); - return new EmbeddingCollection( + return new OpenAIEmbeddingCollection( items.ToList(), model, InternalCreateEmbeddingResponseObject.List, diff --git a/src/Custom/Files/FileClient.cs b/src/Custom/Files/FileClient.cs index 473305f4..1968eaa3 100644 --- a/src/Custom/Files/FileClient.cs +++ b/src/Custom/Files/FileClient.cs @@ -105,7 +105,7 @@ protected internal FileClient(ClientPipeline pipeline, OpenAIClientOptions optio /// A token that can be used to cancel this method call. /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> UploadFileAsync(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default) + public virtual async Task> UploadFileAsync(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default) { Argument.AssertNotNull(file, nameof(file)); Argument.AssertNotNullOrEmpty(filename, nameof(filename)); @@ -117,7 +117,7 @@ public virtual async Task> UploadFileAsync(Stream f using MultipartFormDataBinaryContent content = options.ToMultipartContent(file, filename); ClientResult result = await UploadFileAsync(content, content.ContentType, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Uploads a file that can be used across various operations. @@ -132,7 +132,7 @@ public virtual async Task> UploadFileAsync(Stream f /// A token that can be used to cancel this method call. /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult UploadFile(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default) + public virtual ClientResult UploadFile(Stream file, string filename, FileUploadPurpose purpose, CancellationToken cancellationToken = default) { Argument.AssertNotNull(file, nameof(file)); Argument.AssertNotNullOrEmpty(filename, nameof(filename)); @@ -144,7 +144,7 @@ public virtual ClientResult UploadFile(Stream file, string filen using MultipartFormDataBinaryContent content = options.ToMultipartContent(file, filename); ClientResult result = UploadFile(content, content.ContentType, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Uploads a file that can be used across various operations. @@ -158,7 +158,7 @@ public virtual ClientResult UploadFile(Stream file, string filen /// The intended purpose of the uploaded file. /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual Task> UploadFileAsync(BinaryData file, string filename, FileUploadPurpose purpose) + public virtual Task> UploadFileAsync(BinaryData file, string filename, FileUploadPurpose purpose) { Argument.AssertNotNull(file, nameof(file)); Argument.AssertNotNullOrEmpty(filename, nameof(filename)); @@ -177,7 +177,7 @@ public virtual Task> UploadFileAsync(BinaryData fil /// The intended purpose of the uploaded file. /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult UploadFile(BinaryData file, string filename, FileUploadPurpose purpose) + public virtual ClientResult UploadFile(BinaryData file, string filename, FileUploadPurpose purpose) { Argument.AssertNotNull(file, nameof(file)); Argument.AssertNotNullOrEmpty(filename, nameof(filename)); @@ -195,7 +195,7 @@ public virtual ClientResult UploadFile(BinaryData file, string f /// The intended purpose of the uploaded file. /// was null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> UploadFileAsync(string filePath, FileUploadPurpose purpose) + public virtual async Task> UploadFileAsync(string filePath, FileUploadPurpose purpose) { Argument.AssertNotNullOrEmpty(filePath, nameof(filePath)); @@ -213,7 +213,7 @@ public virtual async Task> UploadFileAsync(string f /// The intended purpose of the uploaded file. /// was null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult UploadFile(string filePath, FileUploadPurpose purpose) + public virtual ClientResult UploadFile(string filePath, FileUploadPurpose purpose) { Argument.AssertNotNullOrEmpty(filePath, nameof(filePath)); @@ -223,36 +223,36 @@ public virtual ClientResult UploadFile(string filePath, FileUplo /// Gets basic information about each of the files belonging to the user's organization. /// A token that can be used to cancel this method call. - public virtual async Task> GetFilesAsync(CancellationToken cancellationToken = default) + public virtual async Task> GetFilesAsync(CancellationToken cancellationToken = default) { ClientResult result = await GetFilesAsync(null, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. /// A token that can be used to cancel this method call. - public virtual ClientResult GetFiles(CancellationToken cancellationToken = default) + public virtual ClientResult GetFiles(CancellationToken cancellationToken = default) { ClientResult result = GetFiles(null, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. /// Only return files with the given purpose. /// A token that can be used to cancel this method call. - public virtual async Task> GetFilesAsync(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default) + public virtual async Task> GetFilesAsync(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default) { ClientResult result = await GetFilesAsync(purpose.ToString(), cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about each of the files belonging to the user's organization. /// Only return files with the given purpose. /// A token that can be used to cancel this method call. - public virtual ClientResult GetFiles(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default) + public virtual ClientResult GetFiles(OpenAIFilePurpose purpose, CancellationToken cancellationToken = default) { ClientResult result = GetFiles(purpose.ToString(), cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFileCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about the specified file. @@ -260,12 +260,12 @@ public virtual ClientResult GetFiles(OpenAIFilePurpose /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) + public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = await GetFileAsync(fileId, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIFileInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about the specified file. @@ -273,12 +273,12 @@ public virtual async Task> GetFileAsync(string file /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult GetFile(string fileId, CancellationToken cancellationToken = default) + public virtual ClientResult GetFile(string fileId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); ClientResult result = GetFile(fileId, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIFileInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIFile.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Deletes the specified file. diff --git a/src/Custom/Files/OpenAIFileInfo.cs b/src/Custom/Files/OpenAIFile.cs similarity index 96% rename from src/Custom/Files/OpenAIFileInfo.cs rename to src/Custom/Files/OpenAIFile.cs index 5557449f..ce4e34b7 100644 --- a/src/Custom/Files/OpenAIFileInfo.cs +++ b/src/Custom/Files/OpenAIFile.cs @@ -3,7 +3,7 @@ namespace OpenAI.Files; [CodeGenModel("OpenAIFile")] -public partial class OpenAIFileInfo +public partial class OpenAIFile { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// The object type, which is always "file". diff --git a/src/Custom/Files/OpenAIFileInfoCollection.Serialization.cs b/src/Custom/Files/OpenAIFileCollection.Serialization.cs similarity index 68% rename from src/Custom/Files/OpenAIFileInfoCollection.Serialization.cs rename to src/Custom/Files/OpenAIFileCollection.Serialization.cs index 751d8be5..2a498dbe 100644 --- a/src/Custom/Files/OpenAIFileInfoCollection.Serialization.cs +++ b/src/Custom/Files/OpenAIFileCollection.Serialization.cs @@ -5,23 +5,23 @@ namespace OpenAI.Files; -[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] -public partial class OpenAIFileInfoCollection : IJsonModel +[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] +public partial class OpenAIFileCollection : IJsonModel { // CUSTOM: // - Serialized the Items property. // - Recovered the serialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - => CustomSerializationHelpers.SerializeInstance(this, SerializeOpenAIFileInfoCollection, writer, options); + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeOpenAIFileCollection, writer, options); - internal static void SerializeOpenAIFileInfoCollection(OpenAIFileInfoCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + internal static void SerializeOpenAIFileCollection(OpenAIFileCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); writer.WritePropertyName("data"u8); writer.WriteStartArray(); foreach (var item in instance.Items) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); writer.WritePropertyName("object"u8); @@ -31,7 +31,7 @@ internal static void SerializeOpenAIFileInfoCollection(OpenAIFileInfoCollection } // CUSTOM: Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - internal static OpenAIFileInfoCollection DeserializeOpenAIFileInfoCollection(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIFileCollection DeserializeOpenAIFileCollection(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -39,7 +39,7 @@ internal static OpenAIFileInfoCollection DeserializeOpenAIFileInfoCollection(Jso { return null; } - IReadOnlyList data = default; + IReadOnlyList data = default; InternalListFilesResponseObject @object = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -47,10 +47,10 @@ internal static OpenAIFileInfoCollection DeserializeOpenAIFileInfoCollection(Jso { if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(OpenAIFileInfo.DeserializeOpenAIFileInfo(item, options)); + array.Add(OpenAIFile.DeserializeOpenAIFile(item, options)); } data = array; continue; @@ -66,7 +66,7 @@ internal static OpenAIFileInfoCollection DeserializeOpenAIFileInfoCollection(Jso } } serializedAdditionalRawData = rawDataDictionary; - return new OpenAIFileInfoCollection(data, @object, serializedAdditionalRawData); + return new OpenAIFileCollection(data, @object, serializedAdditionalRawData); } } diff --git a/src/Custom/Files/OpenAIFileInfoCollection.cs b/src/Custom/Files/OpenAIFileCollection.cs similarity index 78% rename from src/Custom/Files/OpenAIFileInfoCollection.cs rename to src/Custom/Files/OpenAIFileCollection.cs index 9406205b..d1591feb 100644 --- a/src/Custom/Files/OpenAIFileInfoCollection.cs +++ b/src/Custom/Files/OpenAIFileCollection.cs @@ -6,9 +6,9 @@ namespace OpenAI.Files; [CodeGenModel("ListFilesResponse")] [CodeGenSuppress("Data")] -[CodeGenSuppress(nameof(OpenAIFileInfoCollection))] -[CodeGenSuppress(nameof(OpenAIFileInfoCollection), typeof(IReadOnlyList), typeof(InternalListFilesResponseObject))] -public partial class OpenAIFileInfoCollection : ReadOnlyCollection +[CodeGenSuppress(nameof(OpenAIFileCollection))] +[CodeGenSuppress(nameof(OpenAIFileCollection), typeof(IReadOnlyList), typeof(InternalListFilesResponseObject))] +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. @@ -47,28 +47,28 @@ public partial class OpenAIFileInfoCollection : ReadOnlyCollection private IDictionary SerializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// /// is null. - internal OpenAIFileInfoCollection(IEnumerable data) + internal OpenAIFileCollection(IEnumerable data) : base([.. data]) { Argument.AssertNotNull(data, nameof(data)); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// /// /// Keeps track of any properties unknown to the library. - internal OpenAIFileInfoCollection(IReadOnlyList data, InternalListFilesResponseObject @object, IDictionary serializedAdditionalRawData) + internal OpenAIFileCollection(IReadOnlyList data, InternalListFilesResponseObject @object, IDictionary serializedAdditionalRawData) : base([.. data]) { Object = @object; SerializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal OpenAIFileInfoCollection() + /// Initializes a new instance of for deserialization. + internal OpenAIFileCollection() : base([]) { } diff --git a/src/Custom/Files/OpenAIFilesModelFactory.cs b/src/Custom/Files/OpenAIFilesModelFactory.cs index 326e3d32..edb573b5 100644 --- a/src/Custom/Files/OpenAIFilesModelFactory.cs +++ b/src/Custom/Files/OpenAIFilesModelFactory.cs @@ -20,9 +20,9 @@ public static FileDeletionResult FileDeletionResult(string fileId = null, bool d /// Initializes a new instance of . /// A new instance for mocking. - public static OpenAIFileInfo OpenAIFileInfo(string id = null, int? sizeInBytes = null, DateTimeOffset createdAt = default, string filename = null, OpenAIFilePurpose purpose = default, OpenAIFileStatus status = default, string statusDetails = null) + public static OpenAIFile OpenAIFileInfo(string id = null, int? sizeInBytes = null, DateTimeOffset createdAt = default, string filename = null, OpenAIFilePurpose purpose = default, OpenAIFileStatus status = default, string statusDetails = null) { - return new OpenAIFileInfo( + return new OpenAIFile( id, sizeInBytes, createdAt, @@ -34,13 +34,13 @@ public static OpenAIFileInfo OpenAIFileInfo(string id = null, int? sizeInBytes = serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// A new instance for mocking. - public static OpenAIFileInfoCollection OpenAIFileInfoCollection(IEnumerable items = null) + /// Initializes a new instance of . + /// A new instance for mocking. + public static OpenAIFileCollection OpenAIFileCollection(IEnumerable items = null) { - items ??= new List(); + items ??= new List(); - return new OpenAIFileInfoCollection( + return new OpenAIFileCollection( items.ToList(), InternalListFilesResponseObject.List, serializedAdditionalRawData: null); diff --git a/src/Custom/Models/ModelClient.cs b/src/Custom/Models/ModelClient.cs index 9b050a08..73c39625 100644 --- a/src/Custom/Models/ModelClient.cs +++ b/src/Custom/Models/ModelClient.cs @@ -84,18 +84,18 @@ protected internal ModelClient(ClientPipeline pipeline, OpenAIClientOptions opti /// Gets basic information about each of the models that are currently available, such as their corresponding owner and availability. /// A token that can be used to cancel this method call. - public virtual async Task> GetModelsAsync(CancellationToken cancellationToken = default) + public virtual async Task> GetModelsAsync(CancellationToken cancellationToken = default) { ClientResult result = await GetModelsAsync(cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIModelInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIModelCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about each of the models that are currently available, such as their corresponding owner and availability. /// A token that can be used to cancel this method call. - public virtual ClientResult GetModels(CancellationToken cancellationToken = default) + public virtual ClientResult GetModels(CancellationToken cancellationToken = default) { ClientResult result = GetModels(cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIModelInfoCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIModelCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about the specified model, such as its owner and availability. @@ -103,12 +103,12 @@ public virtual ClientResult GetModels(CancellationTok /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetModelAsync(string model, CancellationToken cancellationToken = default) + public virtual async Task> GetModelAsync(string model, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = await GetModelAsync(model, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(OpenAIModelInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIModel.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Gets basic information about the specified model, such as its owner and availability. @@ -116,12 +116,12 @@ public virtual async Task> GetModelAsync(string mo /// A token that can be used to cancel this method call. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual ClientResult GetModel(string model, CancellationToken cancellationToken = default) + public virtual ClientResult GetModel(string model, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(model, nameof(model)); ClientResult result = GetModel(model, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(OpenAIModelInfo.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(OpenAIModel.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Deletes the specified fine-tuned model. diff --git a/src/Custom/Models/OpenAIModelInfo.cs b/src/Custom/Models/OpenAIModel.cs similarity index 94% rename from src/Custom/Models/OpenAIModelInfo.cs rename to src/Custom/Models/OpenAIModel.cs index 1fbb8fdd..a66b41dc 100644 --- a/src/Custom/Models/OpenAIModelInfo.cs +++ b/src/Custom/Models/OpenAIModel.cs @@ -6,7 +6,7 @@ namespace OpenAI.Models; /// Represents information about a single available model entry. /// [CodeGenModel("Model")] -public partial class OpenAIModelInfo +public partial class OpenAIModel { // CUSTOM: Made private. This property does not add value in the context of a strongly-typed class. /// The object type, which is always "model". diff --git a/src/Custom/Models/OpenAIModelInfoCollection.Serialization.cs b/src/Custom/Models/OpenAIModelCollection.Serialization.cs similarity index 68% rename from src/Custom/Models/OpenAIModelInfoCollection.Serialization.cs rename to src/Custom/Models/OpenAIModelCollection.Serialization.cs index 6cfc9383..0c0a0800 100644 --- a/src/Custom/Models/OpenAIModelInfoCollection.Serialization.cs +++ b/src/Custom/Models/OpenAIModelCollection.Serialization.cs @@ -8,16 +8,16 @@ namespace OpenAI.Models; -[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] -public partial class OpenAIModelInfoCollection : IJsonModel +[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] +public partial class OpenAIModelCollection : IJsonModel { // CUSTOM: // - Serialized the Items property. // - Recovered the serialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - => CustomSerializationHelpers.SerializeInstance(this, SerializeOpenAIModelInfoCollection, writer, options); + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeOpenAIModelCollection, writer, options); - internal static void SerializeOpenAIModelInfoCollection(OpenAIModelInfoCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + internal static void SerializeOpenAIModelCollection(OpenAIModelCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); writer.WritePropertyName("object"u8); @@ -26,7 +26,7 @@ internal static void SerializeOpenAIModelInfoCollection(OpenAIModelInfoCollectio writer.WriteStartArray(); foreach (var item in instance.Items) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); writer.WriteSerializedAdditionalRawData(instance.SerializedAdditionalRawData, options); @@ -34,7 +34,7 @@ internal static void SerializeOpenAIModelInfoCollection(OpenAIModelInfoCollectio } // CUSTOM: Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - internal static OpenAIModelInfoCollection DeserializeOpenAIModelInfoCollection(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIModelCollection DeserializeOpenAIModelCollection(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -43,7 +43,7 @@ internal static OpenAIModelInfoCollection DeserializeOpenAIModelInfoCollection(J return null; } InternalListModelsResponseObject @object = default; - IReadOnlyList data = default; + IReadOnlyList data = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -55,10 +55,10 @@ internal static OpenAIModelInfoCollection DeserializeOpenAIModelInfoCollection(J } if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(OpenAIModelInfo.DeserializeOpenAIModelInfo(item, options)); + array.Add(OpenAIModel.DeserializeOpenAIModel(item, options)); } data = array; continue; @@ -69,6 +69,6 @@ internal static OpenAIModelInfoCollection DeserializeOpenAIModelInfoCollection(J } } serializedAdditionalRawData = rawDataDictionary; - return new OpenAIModelInfoCollection(@object, data, serializedAdditionalRawData); + return new OpenAIModelCollection(@object, data, serializedAdditionalRawData); } } \ No newline at end of file diff --git a/src/Custom/Models/OpenAIModelInfoCollection.cs b/src/Custom/Models/OpenAIModelCollection.cs similarity index 79% rename from src/Custom/Models/OpenAIModelInfoCollection.cs rename to src/Custom/Models/OpenAIModelCollection.cs index 773bab8f..c850dc07 100644 --- a/src/Custom/Models/OpenAIModelInfoCollection.cs +++ b/src/Custom/Models/OpenAIModelCollection.cs @@ -10,9 +10,9 @@ namespace OpenAI.Models; /// [CodeGenModel("ListModelsResponse")] [CodeGenSuppress("Data")] -[CodeGenSuppress(nameof(OpenAIModelInfoCollection))] -[CodeGenSuppress(nameof(OpenAIModelInfoCollection), typeof(InternalListModelsResponseObject), typeof(IReadOnlyList))] -public partial class OpenAIModelInfoCollection : ReadOnlyCollection +[CodeGenSuppress(nameof(OpenAIModelCollection))] +[CodeGenSuppress(nameof(OpenAIModelCollection), typeof(InternalListModelsResponseObject), typeof(IReadOnlyList))] +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. @@ -51,28 +51,28 @@ public partial class OpenAIModelInfoCollection : ReadOnlyCollection private IDictionary SerializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// /// is null. - internal OpenAIModelInfoCollection(IEnumerable data) + internal OpenAIModelCollection(IEnumerable data) : base([.. data]) { Argument.AssertNotNull(data, nameof(data)); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// /// /// Keeps track of any properties unknown to the library. - internal OpenAIModelInfoCollection(InternalListModelsResponseObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + internal OpenAIModelCollection(InternalListModelsResponseObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) : base([.. data]) { Object = @object; SerializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal OpenAIModelInfoCollection() + /// Initializes a new instance of for deserialization. + internal OpenAIModelCollection() : base([]) { } diff --git a/src/Custom/Models/OpenAIModelsModelFactory.cs b/src/Custom/Models/OpenAIModelsModelFactory.cs index cd2eee90..8413b55c 100644 --- a/src/Custom/Models/OpenAIModelsModelFactory.cs +++ b/src/Custom/Models/OpenAIModelsModelFactory.cs @@ -18,11 +18,11 @@ public static ModelDeletionResult ModelDeletionResult(string modelId = null, boo serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// A new instance for mocking. - public static OpenAIModelInfo OpenAIModelInfo(string id = null, DateTimeOffset createdAt = default, string ownedBy = null) + /// Initializes a new instance of . + /// A new instance for mocking. + public static OpenAIModel OpenAIModel(string id = null, DateTimeOffset createdAt = default, string ownedBy = null) { - return new OpenAIModelInfo( + return new OpenAIModel( id, createdAt, InternalModelObject.Model, @@ -30,13 +30,13 @@ public static OpenAIModelInfo OpenAIModelInfo(string id = null, DateTimeOffset c serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// A new instance for mocking. - public static OpenAIModelInfoCollection OpenAIModelInfoCollection(IEnumerable items = null) + /// Initializes a new instance of . + /// A new instance for mocking. + public static OpenAIModelCollection OpenAIModelCollection(IEnumerable items = null) { - items ??= new List(); + items ??= new List(); - return new OpenAIModelInfoCollection( + return new OpenAIModelCollection( InternalListModelsResponseObject.List, items.ToList(), serializedAdditionalRawData: null); diff --git a/src/Custom/Moderations/Internal/InternalModerationCategories.cs b/src/Custom/Moderations/Internal/InternalModerationCategories.cs new file mode 100644 index 00000000..1a8898c2 --- /dev/null +++ b/src/Custom/Moderations/Internal/InternalModerationCategories.cs @@ -0,0 +1,7 @@ +namespace OpenAI.Moderations; + +[CodeGenModel("CreateModerationResponseResultCategories")] +internal partial class InternalModerationCategories +{ +} + diff --git a/src/Custom/Moderations/Internal/InternalModerationCategoryScores.cs b/src/Custom/Moderations/Internal/InternalModerationCategoryScores.cs new file mode 100644 index 00000000..464a1a5d --- /dev/null +++ b/src/Custom/Moderations/Internal/InternalModerationCategoryScores.cs @@ -0,0 +1,6 @@ +namespace OpenAI.Moderations; + +[CodeGenModel("CreateModerationResponseResultCategoryScores")] +internal partial class InternalModerationCategoryScores +{ +} diff --git a/src/Custom/Moderations/ModerationCategories.cs b/src/Custom/Moderations/ModerationCategories.cs deleted file mode 100644 index a5cbbe8b..00000000 --- a/src/Custom/Moderations/ModerationCategories.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace OpenAI.Moderations; - -[CodeGenModel("CreateModerationResponseResultCategories")] -public partial class ModerationCategories -{ -} diff --git a/src/Custom/Moderations/ModerationCategory.cs b/src/Custom/Moderations/ModerationCategory.cs new file mode 100644 index 00000000..d36fc620 --- /dev/null +++ b/src/Custom/Moderations/ModerationCategory.cs @@ -0,0 +1,13 @@ +namespace OpenAI.Moderations; + +public partial class ModerationCategory +{ + internal ModerationCategory(bool flagged, float score) + { + Flagged = flagged; + Score = score; + } + + public bool Flagged { get; } + public float Score { get; } +} diff --git a/src/Custom/Moderations/ModerationCategoryScores.cs b/src/Custom/Moderations/ModerationCategoryScores.cs deleted file mode 100644 index 34b093f1..00000000 --- a/src/Custom/Moderations/ModerationCategoryScores.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace OpenAI.Moderations; - -[CodeGenModel("CreateModerationResponseResultCategoryScores")] -public partial class ModerationCategoryScores -{ -} diff --git a/src/Custom/Moderations/ModerationClient.cs b/src/Custom/Moderations/ModerationClient.cs index 38d5ba6c..2f590206 100644 --- a/src/Custom/Moderations/ModerationClient.cs +++ b/src/Custom/Moderations/ModerationClient.cs @@ -112,7 +112,7 @@ public virtual async Task> ClassifyTextAsync(stri using BinaryContent content = options.ToBinaryContent(); ClientResult result = await ClassifyTextAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(ModerationCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); } /// Classifies if the text input is potentially harmful across several categories. @@ -129,7 +129,7 @@ public virtual ClientResult ClassifyText(string input, Cancell using BinaryContent content = options.ToBinaryContent(); ClientResult result = ClassifyText(content, cancellationToken.ToRequestOptions()); - return ClientResult.FromValue(ModerationCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); + return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()).FirstOrDefault(), result.GetRawResponse()); } /// Classifies if the text inputs are potentially harmful across several categories. @@ -137,7 +137,7 @@ public virtual ClientResult ClassifyText(string input, Cancell /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual async Task> ClassifyTextAsync(IEnumerable inputs, CancellationToken cancellationToken = default) + public virtual async Task> ClassifyTextAsync(IEnumerable inputs, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -146,7 +146,7 @@ public virtual async Task> ClassifyTextAsync( using BinaryContent content = options.ToBinaryContent(); ClientResult result = await ClassifyTextAsync(content, cancellationToken.ToRequestOptions()).ConfigureAwait(false); - return ClientResult.FromValue(ModerationCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); + return ClientResult.FromValue(ModerationResultCollection.FromResponse(result.GetRawResponse()), result.GetRawResponse()); } /// Classifies if the text inputs are potentially harmful across several categories. @@ -154,7 +154,7 @@ public virtual async Task> ClassifyTextAsync( /// A token that can be used to cancel this method call. /// is null. /// is an empty collection, and was expected to be non-empty. - public virtual ClientResult ClassifyText(IEnumerable inputs, CancellationToken cancellationToken = default) + public virtual ClientResult ClassifyText(IEnumerable inputs, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(inputs, nameof(inputs)); @@ -163,7 +163,7 @@ public virtual ClientResult ClassifyText(IEnumerable.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] + public partial class ModerationResult : IJsonModel + { + // CUSTOM: + // - Serializes `ModerationCategories` and `ModerationCategoryScores` properties. + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ModerationResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (SerializedAdditionalRawData?.ContainsKey("flagged") != true) + { + writer.WritePropertyName("flagged"u8); + writer.WriteBooleanValue(Flagged); + } + if (SerializedAdditionalRawData?.ContainsKey("categories") != true) + { + writer.WritePropertyName("categories"u8); + InternalModerationCategories internalCategories = new InternalModerationCategories( + hate: Hate.Flagged, + hateThreatening: HateThreatening.Flagged, + harassment: Harassment.Flagged, + harassmentThreatening: HarassmentThreatening.Flagged, + selfHarm: SelfHarm.Flagged, + selfHarmIntent: SelfHarmIntent.Flagged, + selfHarmInstructions: SelfHarmInstructions.Flagged, + sexual: Sexual.Flagged, + sexualMinors: SexualMinors.Flagged, + violence: Violence.Flagged, + violenceGraphic: ViolenceGraphic.Flagged); + writer.WriteObjectValue(internalCategories, options); + } + if (SerializedAdditionalRawData?.ContainsKey("category_scores") != true) + { + writer.WritePropertyName("category_scores"u8); + InternalModerationCategoryScores internalCategoryScores = new InternalModerationCategoryScores( + hate: Hate.Score, + hateThreatening: HateThreatening.Score, + harassment: Harassment.Score, + harassmentThreatening: HarassmentThreatening.Score, + selfHarm: SelfHarm.Score, + selfHarmIntent: SelfHarmIntent.Score, + selfHarmInstructions: SelfHarmInstructions.Score, + sexual: Sexual.Score, + sexualMinors: SexualMinors.Score, + violence: Violence.Score, + violenceGraphic: ViolenceGraphic.Score); + writer.WriteObjectValue(internalCategoryScores, 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(); + } + + internal static ModerationResult DeserializeModerationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool flagged = default; + + InternalModerationCategories internalCategories = default; + InternalModerationCategoryScores internalCategoryScores = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("flagged"u8)) + { + flagged = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("categories"u8)) + { + internalCategories = InternalModerationCategories.DeserializeInternalModerationCategories(property.Value, options); + continue; + } + if (property.NameEquals("category_scores"u8)) + { + internalCategoryScores = InternalModerationCategoryScores.DeserializeInternalModerationCategoryScores(property.Value, options); + continue; + } + if (true) + { + rawDataDictionary ??= new Dictionary(); + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ModerationResult( + flagged: flagged, + hate: new ModerationCategory(internalCategories.Hate, internalCategoryScores.Hate), + hateThreatening: new ModerationCategory(internalCategories.HateThreatening, internalCategoryScores.HateThreatening), + harassment: new ModerationCategory(internalCategories.Harassment, internalCategoryScores.Harassment), + harassmentThreatening: new ModerationCategory(internalCategories.HarassmentThreatening, internalCategoryScores.HarassmentThreatening), + selfHarm: new ModerationCategory(internalCategories.SelfHarm, internalCategoryScores.SelfHarm), + selfHarmIntent: new ModerationCategory(internalCategories.SelfHarmIntent, internalCategoryScores.SelfHarmIntent), + selfHarmInstructions: new ModerationCategory(internalCategories.SelfHarmInstructions, internalCategoryScores.SelfHarmInstructions), + sexual: new ModerationCategory(internalCategories.Sexual, internalCategoryScores.Sexual), + sexualMinors: new ModerationCategory(internalCategories.SexualMinors, internalCategoryScores.SexualMinors), + violence: new ModerationCategory(internalCategories.Violence, internalCategoryScores.Violence), + violenceGraphic: new ModerationCategory(internalCategories.ViolenceGraphic, internalCategoryScores.ViolenceGraphic), + serializedAdditionalRawData: serializedAdditionalRawData); + } + } +} diff --git a/src/Custom/Moderations/ModerationResult.cs b/src/Custom/Moderations/ModerationResult.cs index 78e95f25..320230ad 100644 --- a/src/Custom/Moderations/ModerationResult.cs +++ b/src/Custom/Moderations/ModerationResult.cs @@ -1,6 +1,77 @@ +using System.Collections.Generic; +using System; + namespace OpenAI.Moderations; +// CUSTOM: +// - Removes the redundant classes `ModerationCategories` and `ModerationCategoryScores` and moves their properties into this type. [CodeGenModel("CreateModerationResponseResult")] +[CodeGenSuppress("Categories")] +[CodeGenSuppress("CategoryScores")] +[CodeGenSuppress(nameof(ModerationResult), typeof(bool), typeof(InternalModerationCategories), typeof(InternalModerationCategoryScores))] +[CodeGenSuppress(nameof(ModerationResult), typeof(bool), typeof(InternalModerationCategories), typeof(InternalModerationCategoryScores), typeof(IDictionary))] public partial class ModerationResult { + internal IDictionary SerializedAdditionalRawData { get; set; } + + internal ModerationResult(bool flagged, ModerationCategory hate, ModerationCategory hateThreatening, ModerationCategory harassment, ModerationCategory harassmentThreatening, ModerationCategory selfHarm, ModerationCategory selfHarmIntent, ModerationCategory selfHarmInstructions, ModerationCategory sexual, ModerationCategory sexualMinors, ModerationCategory violence, ModerationCategory violenceGraphic) + { + Flagged = flagged; + Hate = hate; + HateThreatening = hateThreatening; + Harassment = harassment; + HarassmentThreatening = harassmentThreatening; + SelfHarm = selfHarm; + SelfHarmIntent = selfHarmIntent; + SelfHarmInstructions = selfHarmInstructions; + Sexual = sexual; + SexualMinors = sexualMinors; + Violence = violence; + ViolenceGraphic = violenceGraphic; + } + + internal ModerationResult(bool flagged, ModerationCategory hate, ModerationCategory hateThreatening, ModerationCategory harassment, ModerationCategory harassmentThreatening, ModerationCategory selfHarm, ModerationCategory selfHarmIntent, ModerationCategory selfHarmInstructions, ModerationCategory sexual, ModerationCategory sexualMinors, ModerationCategory violence, ModerationCategory violenceGraphic, IDictionary serializedAdditionalRawData) + { + Flagged = flagged; + Hate = hate; + HateThreatening = hateThreatening; + Harassment = harassment; + HarassmentThreatening = harassmentThreatening; + SelfHarm = selfHarm; + SelfHarmIntent = selfHarmIntent; + SelfHarmInstructions = selfHarmInstructions; + Sexual = sexual; + SexualMinors = sexualMinors; + Violence = violence; + ViolenceGraphic = violenceGraphic; + SerializedAdditionalRawData = serializedAdditionalRawData; + } + + internal ModerationResult() + { + } + + public bool Flagged { get; } + + public ModerationCategory Hate { get; } + + public ModerationCategory HateThreatening { get; } + + public ModerationCategory Harassment { get; } + + public ModerationCategory HarassmentThreatening { get; } + + public ModerationCategory SelfHarm { get; } + + public ModerationCategory SelfHarmIntent { get; } + + public ModerationCategory SelfHarmInstructions { get; } + + public ModerationCategory Sexual { get; } + + public ModerationCategory SexualMinors { get; } + + public ModerationCategory Violence { get; } + + public ModerationCategory ViolenceGraphic { get; } } diff --git a/src/Custom/Moderations/ModerationCollection.Serialization..cs b/src/Custom/Moderations/ModerationResultCollection.Serialization..cs similarity index 77% rename from src/Custom/Moderations/ModerationCollection.Serialization..cs rename to src/Custom/Moderations/ModerationResultCollection.Serialization..cs index 1bf783f1..12d54739 100644 --- a/src/Custom/Moderations/ModerationCollection.Serialization..cs +++ b/src/Custom/Moderations/ModerationResultCollection.Serialization..cs @@ -9,16 +9,16 @@ namespace OpenAI.Moderations; -[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] -public partial class ModerationCollection : IJsonModel +[CodeGenSuppress("global::System.ClientModel.Primitives.IJsonModel.Write", typeof(Utf8JsonWriter), typeof(ModelReaderWriterOptions))] +public partial class ModerationResultCollection : IJsonModel { // CUSTOM: // - Serialized the Items property. // - Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - => CustomSerializationHelpers.SerializeInstance(this, SerializeModerationCollection, writer, options); + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + => CustomSerializationHelpers.SerializeInstance(this, SerializeModerationResultCollection, writer, options); - internal static void SerializeModerationCollection(ModerationCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) + internal static void SerializeModerationResultCollection(ModerationResultCollection instance, Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); writer.WritePropertyName("id"u8); @@ -37,7 +37,7 @@ internal static void SerializeModerationCollection(ModerationCollection instance } // CUSTOM: Recovered the deserialization of SerializedAdditionalRawData. See https://github.com/Azure/autorest.csharp/issues/4636. - internal static ModerationCollection DeserializeModerationCollection(JsonElement element, ModelReaderWriterOptions options = null) + internal static ModerationResultCollection DeserializeModerationResultCollection(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -78,6 +78,6 @@ internal static ModerationCollection DeserializeModerationCollection(JsonElement } } serializedAdditionalRawData = rawDataDictionary; - return new ModerationCollection(id, model, results, serializedAdditionalRawData); + return new ModerationResultCollection(id, model, results, serializedAdditionalRawData); } } diff --git a/src/Custom/Moderations/ModerationCollection.cs b/src/Custom/Moderations/ModerationResultCollection.cs similarity index 80% rename from src/Custom/Moderations/ModerationCollection.cs rename to src/Custom/Moderations/ModerationResultCollection.cs index ed2a4c6d..cc1f1ccc 100644 --- a/src/Custom/Moderations/ModerationCollection.cs +++ b/src/Custom/Moderations/ModerationResultCollection.cs @@ -6,9 +6,9 @@ namespace OpenAI.Moderations; [CodeGenModel("CreateModerationResponse")] [CodeGenSuppress("Results")] -[CodeGenSuppress(nameof(ModerationCollection))] -[CodeGenSuppress(nameof(ModerationCollection), typeof(string), typeof(string), typeof(IReadOnlyList))] -public partial class ModerationCollection : ReadOnlyCollection +[CodeGenSuppress(nameof(ModerationResultCollection))] +[CodeGenSuppress(nameof(ModerationResultCollection), typeof(string), typeof(string), typeof(IReadOnlyList))] +public partial class ModerationResultCollection : ReadOnlyCollection { // CUSTOM: Recovered this field. See https://github.com/Azure/autorest.csharp/issues/4636. /// @@ -43,12 +43,12 @@ public partial class ModerationCollection : ReadOnlyCollection /// private IDictionary SerializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The unique identifier for the moderation request. /// The model used to generate the moderation results. /// A list of moderation objects. /// , or is null. - internal ModerationCollection(string id, string model, IEnumerable results) + internal ModerationResultCollection(string id, string model, IEnumerable results) : base([.. results]) { Argument.AssertNotNull(id, nameof(id)); @@ -59,12 +59,12 @@ internal ModerationCollection(string id, string model, IEnumerable Initializes a new instance of . + /// Initializes a new instance of . /// The unique identifier for the moderation request. /// The model used to generate the moderation results. /// A list of moderation objects. /// Keeps track of any properties unknown to the library. - internal ModerationCollection(string id, string model, IReadOnlyList results, IDictionary serializedAdditionalRawData) + internal ModerationResultCollection(string id, string model, IReadOnlyList results, IDictionary serializedAdditionalRawData) : base([.. results]) { Id = id; @@ -72,8 +72,8 @@ internal ModerationCollection(string id, string model, IReadOnlyList Initializes a new instance of for deserialization. - internal ModerationCollection() + /// Initializes a new instance of for deserialization. + internal ModerationResultCollection() : base([]) { } diff --git a/src/Custom/Moderations/OpenAIModerationsModelFactory.cs b/src/Custom/Moderations/OpenAIModerationsModelFactory.cs index f81a2a59..d88a7253 100644 --- a/src/Custom/Moderations/OpenAIModerationsModelFactory.cs +++ b/src/Custom/Moderations/OpenAIModerationsModelFactory.cs @@ -6,51 +6,20 @@ namespace OpenAI.Moderations; /// Model factory for models. public static partial class OpenAIModerationsModelFactory { - /// Initializes a new instance of . - /// A new instance for mocking. - public static ModerationCategories ModerationCategories(bool hate = default, bool hateThreatening = default, bool harassment = default, bool harassmentThreatening = default, bool selfHarm = default, bool selfHarmIntent = default, bool selfHarmInstructions = default, bool sexual = default, bool sexualMinors = default, bool violence = default, bool violenceGraphic = default) + /// Initializes a new instance of . + /// A new instance for mocking. + public static ModerationCategory ModerationCategory(bool flagged = default, float score = default) { - return new ModerationCategories( - hate, - hateThreatening, - harassment, - harassmentThreatening, - selfHarm, - selfHarmIntent, - selfHarmInstructions, - sexual, - sexualMinors, - violence, - violenceGraphic, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// A new instance for mocking. - public static ModerationCategoryScores ModerationCategoryScores(float hate = default, float hateThreatening = default, float harassment = default, float harassmentThreatening = default, float selfHarm = default, float selfHarmIntent = default, float selfHarmInstructions = default, float sexual = default, float sexualMinors = default, float violence = default, float violenceGraphic = default) - { - return new ModerationCategoryScores( - hate, - hateThreatening, - harassment, - harassmentThreatening, - selfHarm, - selfHarmIntent, - selfHarmInstructions, - sexual, - sexualMinors, - violence, - violenceGraphic, - serializedAdditionalRawData: null); + return new ModerationCategory(flagged, score); } - /// Initializes a new instance of . - /// A new instance for mocking. - public static ModerationCollection ModerationCollection(string id = null, string model = null, IEnumerable items = null) + /// Initializes a new instance of . + /// A new instance for mocking. + public static ModerationResultCollection ModerationResultCollection(string id = null, string model = null, IEnumerable items = null) { items ??= new List(); - return new ModerationCollection( + return new ModerationResultCollection( id, model, items.ToList(), @@ -59,12 +28,21 @@ public static ModerationCollection ModerationCollection(string id = null, string /// Initializes a new instance of . /// A new instance for mocking. - public static ModerationResult ModerationResult(bool flagged = default, ModerationCategories categories = null, ModerationCategoryScores categoryScores = null) + public static ModerationResult ModerationResult(bool flagged = default, ModerationCategory hate = default, ModerationCategory hateThreatening = default, ModerationCategory harassment = default, ModerationCategory harassmentThreatening = default, ModerationCategory selfHarm = default, ModerationCategory selfHarmIntent = default, ModerationCategory selfHarmInstructions = default, ModerationCategory sexual = default, ModerationCategory sexualMinors = default, ModerationCategory violence = default, ModerationCategory violenceGraphic = default) { return new ModerationResult( flagged, - categories, - categoryScores, + hate, + hateThreatening, + harassment, + harassmentThreatening, + selfHarm, + selfHarmIntent, + selfHarmInstructions, + sexual, + sexualMinors, + violence, + violenceGraphic, serializedAdditionalRawData: null); } } diff --git a/src/Custom/OpenAIModelFactory.cs b/src/Custom/OpenAIModelFactory.cs index bd049d8c..18d762f1 100644 --- a/src/Custom/OpenAIModelFactory.cs +++ b/src/Custom/OpenAIModelFactory.cs @@ -8,29 +8,29 @@ namespace OpenAI; [CodeGenModel("OpenAIModelFactory")] internal static partial class OpenAIModelFactory { - /// Initializes a new instance of . + /// Initializes a new instance of . /// The list of embeddings generated by the model. /// The name of the model used to generate the embedding. /// The usage information for the request. - /// A new instance for mocking. - public static EmbeddingCollection EmbeddingCollection(IEnumerable data = null, EmbeddingTokenUsage usage = null, string model = null) + /// A new instance for mocking. + public static OpenAIEmbeddingCollection OpenAIEmbeddingCollection(IEnumerable data = null, EmbeddingTokenUsage usage = null, string model = null) { - data ??= new List(); + data ??= new List(); - return new EmbeddingCollection(data?.ToList(), model, InternalCreateEmbeddingResponseObject.List, usage, serializedAdditionalRawData: null); + return new OpenAIEmbeddingCollection(data?.ToList(), model, InternalCreateEmbeddingResponseObject.List, usage, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The index of the embedding in the list of embeddings. /// /// The embedding vector, which is a list of floats. The length of vector depends on the model as /// listed in the [embedding guide](/docs/guides/embeddings). /// - /// A new instance for mocking. - public static Embedding Embedding(ReadOnlyMemory vector = default, int index = default) + /// A new instance for mocking. + public static OpenAIEmbedding OpenAIEmbedding(ReadOnlyMemory vector = default, int index = default) { // TODO: Vector must be converted to base64-encoded string. - return new Embedding(index, BinaryData.FromObjectAsJson(vector), InternalEmbeddingObject.Embedding, serializedAdditionalRawData: null); + return new OpenAIEmbedding(index, BinaryData.FromObjectAsJson(vector), InternalEmbeddingObject.Embedding, serializedAdditionalRawData: null); } } diff --git a/src/Custom/VectorStores/VectorStoreClient.Convenience.cs b/src/Custom/VectorStores/VectorStoreClient.Convenience.cs index d516fd0a..d067da35 100644 --- a/src/Custom/VectorStores/VectorStoreClient.Convenience.cs +++ b/src/Custom/VectorStores/VectorStoreClient.Convenience.cs @@ -66,7 +66,7 @@ public virtual ClientResult DeleteVectorStore(VectorS /// /// A instance that represents the new association. /// - public virtual Task> AddFileToVectorStoreAsync(VectorStore vectorStore, OpenAIFileInfo file) + public virtual Task> AddFileToVectorStoreAsync(VectorStore vectorStore, OpenAIFile file) => AddFileToVectorStoreAsync(vectorStore?.Id, file?.Id); /// @@ -77,7 +77,7 @@ public virtual Task> AddFileToVectorSto /// /// A instance that represents the new association. /// - public virtual ClientResult AddFileToVectorStore(VectorStore vectorStore, OpenAIFileInfo file) + public virtual ClientResult AddFileToVectorStore(VectorStore vectorStore, OpenAIFile file) => AddFileToVectorStore(vectorStore?.Id, file?.Id); /// @@ -117,7 +117,7 @@ public virtual CollectionResult GetFileAssociations( /// A instance. public virtual Task> GetFileAssociationAsync( VectorStore vectorStore, - OpenAIFileInfo file) + OpenAIFile file) => GetFileAssociationAsync(vectorStore?.Id, file?.Id); /// @@ -129,7 +129,7 @@ public virtual Task> GetFileAssociation /// A instance. public virtual ClientResult GetFileAssociation( VectorStore vectorStore, - OpenAIFileInfo file) + OpenAIFile file) => GetFileAssociation(vectorStore?.Id, file?.Id); /// @@ -137,12 +137,12 @@ public virtual ClientResult GetFileAssociation( /// store. /// /// - /// This does not delete the file. To delete the file, use . + /// This does not delete the file. To delete the file, use . /// /// The vector store that the file should be removed from. /// The file to remove from the vector store. /// A instance. - public virtual Task> RemoveFileFromStoreAsync(VectorStore vectorStore, OpenAIFileInfo file) + public virtual Task> RemoveFileFromStoreAsync(VectorStore vectorStore, OpenAIFile file) => RemoveFileFromStoreAsync(vectorStore?.Id, file?.Id); /// @@ -150,12 +150,12 @@ public virtual Task> RemoveFileFromStor /// store. /// /// - /// This does not delete the file. To delete the file, use . + /// This does not delete the file. To delete the file, use . /// /// The vector store that the file should be removed from. /// The file to remove from the vector store. /// A instance. - public virtual ClientResult RemoveFileFromStore(VectorStore vectorStore, OpenAIFileInfo file) + public virtual ClientResult RemoveFileFromStore(VectorStore vectorStore, OpenAIFile file) => RemoveFileFromStore(vectorStore?.Id, file?.Id); /// @@ -164,7 +164,7 @@ public virtual ClientResult RemoveFileFromStore(Vect /// The vector store to associate files with. /// The files to associate with the vector store. /// A instance representing the batch operation. - public virtual Task> CreateBatchFileJobAsync(VectorStore vectorStore, IEnumerable files) + public virtual Task> CreateBatchFileJobAsync(VectorStore vectorStore, IEnumerable files) => CreateBatchFileJobAsync(vectorStore?.Id, files?.Select(file => file.Id)); /// @@ -173,7 +173,7 @@ public virtual Task> CreateBatchFileJobAsy /// The vector store to associate files with. /// The files to associate with the vector store. /// A instance representing the batch operation. - public virtual ClientResult CreateBatchFileJob(VectorStore vectorStore, IEnumerable files) + public virtual ClientResult CreateBatchFileJob(VectorStore vectorStore, IEnumerable files) => CreateBatchFileJob(vectorStore?.Id, files?.Select(file => file.Id)); /// diff --git a/src/Generated/Models/ChatCompletionOptions.Serialization.cs b/src/Generated/Models/ChatCompletionOptions.Serialization.cs index 018cb900..66e35c7f 100644 --- a/src/Generated/Models/ChatCompletionOptions.Serialization.cs +++ b/src/Generated/Models/ChatCompletionOptions.Serialization.cs @@ -231,10 +231,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW writer.WritePropertyName("tool_choice"u8); writer.WriteObjectValue(ToolChoice, options); } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(ParallelToolCallsEnabled)) + if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(AllowParallelToolCalls)) { writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(ParallelToolCallsEnabled.Value); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); } if (SerializedAdditionalRawData?.ContainsKey("user") != true && Optional.IsDefined(EndUserId)) { diff --git a/src/Generated/Models/ChatCompletionOptions.cs b/src/Generated/Models/ChatCompletionOptions.cs index 4e3e063b..342461bb 100644 --- a/src/Generated/Models/ChatCompletionOptions.cs +++ b/src/Generated/Models/ChatCompletionOptions.cs @@ -12,7 +12,7 @@ public partial class ChatCompletionOptions { internal IDictionary SerializedAdditionalRawData { get; set; } - internal ChatCompletionOptions(IList messages, InternalCreateChatCompletionRequestModel model, 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? parallelToolCallsEnabled, string endUserId, ChatFunctionChoice functionChoice, IList functions, IDictionary serializedAdditionalRawData) + internal ChatCompletionOptions(IList messages, InternalCreateChatCompletionRequestModel model, 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) { Messages = messages; Model = model; @@ -34,7 +34,7 @@ internal ChatCompletionOptions(IList messages, InternalCreateChatCo TopP = topP; Tools = tools; ToolChoice = toolChoice; - ParallelToolCallsEnabled = parallelToolCallsEnabled; + AllowParallelToolCalls = allowParallelToolCalls; EndUserId = endUserId; FunctionChoice = functionChoice; Functions = functions; diff --git a/src/Generated/Models/EmbeddingCollection.Serialization.cs b/src/Generated/Models/EmbeddingCollection.Serialization.cs deleted file mode 100644 index d569d559..00000000 --- a/src/Generated/Models/EmbeddingCollection.Serialization.cs +++ /dev/null @@ -1,68 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace OpenAI.Embeddings -{ - public partial class EmbeddingCollection : IJsonModel - { - EmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EmbeddingCollection)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEmbeddingCollection(document.RootElement, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var 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(EmbeddingCollection)} does not support writing '{options.Format}' format."); - } - } - - EmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeEmbeddingCollection(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EmbeddingCollection)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static EmbeddingCollection FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeEmbeddingCollection(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs b/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs index 52037989..ae3a1561 100644 --- a/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs +++ b/src/Generated/Models/EmbeddingTokenUsage.Serialization.cs @@ -24,12 +24,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); - writer.WriteNumberValue(InputTokens); + writer.WriteNumberValue(InputTokenCount); } if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); - writer.WriteNumberValue(TotalTokens); + writer.WriteNumberValue(TotalTokenCount); } if (SerializedAdditionalRawData != null) { diff --git a/src/Generated/Models/EmbeddingTokenUsage.cs b/src/Generated/Models/EmbeddingTokenUsage.cs index 5234ccde..ab5e300d 100644 --- a/src/Generated/Models/EmbeddingTokenUsage.cs +++ b/src/Generated/Models/EmbeddingTokenUsage.cs @@ -10,22 +10,21 @@ namespace OpenAI.Embeddings public partial class EmbeddingTokenUsage { internal IDictionary SerializedAdditionalRawData { get; set; } - internal EmbeddingTokenUsage(int inputTokens, int totalTokens) + internal EmbeddingTokenUsage(int inputTokenCount, int totalTokenCount) { - InputTokens = inputTokens; - TotalTokens = totalTokens; + InputTokenCount = inputTokenCount; + TotalTokenCount = totalTokenCount; } - internal EmbeddingTokenUsage(int inputTokens, int totalTokens, IDictionary serializedAdditionalRawData) + internal EmbeddingTokenUsage(int inputTokenCount, int totalTokenCount, IDictionary serializedAdditionalRawData) { - InputTokens = inputTokens; - TotalTokens = totalTokens; + InputTokenCount = inputTokenCount; + TotalTokenCount = totalTokenCount; SerializedAdditionalRawData = serializedAdditionalRawData; } internal EmbeddingTokenUsage() { } - public int TotalTokens { get; } } } diff --git a/src/Generated/Models/ModerationCategories.Serialization.cs b/src/Generated/Models/InternalModerationCategories.Serialization.cs similarity index 80% rename from src/Generated/Models/ModerationCategories.Serialization.cs rename to src/Generated/Models/InternalModerationCategories.Serialization.cs index f8bc1c57..1b62ce32 100644 --- a/src/Generated/Models/ModerationCategories.Serialization.cs +++ b/src/Generated/Models/InternalModerationCategories.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Moderations { - public partial class ModerationCategories : IJsonModel + internal partial class InternalModerationCategories : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationCategories)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategories)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -98,19 +98,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr writer.WriteEndObject(); } - ModerationCategories IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModerationCategories IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationCategories)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategories)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeModerationCategories(document.RootElement, options); + return DeserializeInternalModerationCategories(document.RootElement, options); } - internal static ModerationCategories DeserializeModerationCategories(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModerationCategories DeserializeInternalModerationCategories(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -195,7 +195,7 @@ internal static ModerationCategories DeserializeModerationCategories(JsonElement } } serializedAdditionalRawData = rawDataDictionary; - return new ModerationCategories( + return new InternalModerationCategories( hate, hateThreatening, harassment, @@ -210,41 +210,41 @@ internal static ModerationCategories DeserializeModerationCategories(JsonElement serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(ModerationCategories)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategories)} does not support writing '{options.Format}' format."); } } - ModerationCategories IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalModerationCategories IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeModerationCategories(document.RootElement, options); + return DeserializeInternalModerationCategories(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ModerationCategories)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategories)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationCategories FromResponse(PipelineResponse response) + internal static InternalModerationCategories FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationCategories(document.RootElement); + return DeserializeInternalModerationCategories(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/ModerationCategories.cs b/src/Generated/Models/InternalModerationCategories.cs similarity index 71% rename from src/Generated/Models/ModerationCategories.cs rename to src/Generated/Models/InternalModerationCategories.cs index 978eaf4e..667823ba 100644 --- a/src/Generated/Models/ModerationCategories.cs +++ b/src/Generated/Models/InternalModerationCategories.cs @@ -7,10 +7,10 @@ namespace OpenAI.Moderations { - public partial class ModerationCategories + internal partial class InternalModerationCategories { internal IDictionary SerializedAdditionalRawData { get; set; } - internal ModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, bool selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic) + internal InternalModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, bool selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic) { Hate = hate; HateThreatening = hateThreatening; @@ -25,7 +25,7 @@ internal ModerationCategories(bool hate, bool hateThreatening, bool harassment, ViolenceGraphic = violenceGraphic; } - internal ModerationCategories(bool hate, bool hateThreatening, bool harassment, bool harassmentThreatening, 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 selfHarm, bool selfHarmIntent, bool selfHarmInstructions, bool sexual, bool sexualMinors, bool violence, bool violenceGraphic, IDictionary serializedAdditionalRawData) { Hate = hate; HateThreatening = hateThreatening; @@ -41,7 +41,7 @@ internal ModerationCategories(bool hate, bool hateThreatening, bool harassment, SerializedAdditionalRawData = serializedAdditionalRawData; } - internal ModerationCategories() + internal InternalModerationCategories() { } diff --git a/src/Generated/Models/ModerationCategoryScores.Serialization.cs b/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs similarity index 79% rename from src/Generated/Models/ModerationCategoryScores.Serialization.cs rename to src/Generated/Models/InternalModerationCategoryScores.Serialization.cs index 52df6f3f..f822d126 100644 --- a/src/Generated/Models/ModerationCategoryScores.Serialization.cs +++ b/src/Generated/Models/InternalModerationCategoryScores.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Moderations { - public partial class ModerationCategoryScores : IJsonModel + internal partial class InternalModerationCategoryScores : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationCategoryScores)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategoryScores)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -98,19 +98,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead writer.WriteEndObject(); } - ModerationCategoryScores IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + InternalModerationCategoryScores IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationCategoryScores)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategoryScores)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeModerationCategoryScores(document.RootElement, options); + return DeserializeInternalModerationCategoryScores(document.RootElement, options); } - internal static ModerationCategoryScores DeserializeModerationCategoryScores(JsonElement element, ModelReaderWriterOptions options = null) + internal static InternalModerationCategoryScores DeserializeInternalModerationCategoryScores(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -195,7 +195,7 @@ internal static ModerationCategoryScores DeserializeModerationCategoryScores(Jso } } serializedAdditionalRawData = rawDataDictionary; - return new ModerationCategoryScores( + return new InternalModerationCategoryScores( hate, hateThreatening, harassment, @@ -210,41 +210,41 @@ internal static ModerationCategoryScores DeserializeModerationCategoryScores(Jso serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(ModerationCategoryScores)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategoryScores)} does not support writing '{options.Format}' format."); } } - ModerationCategoryScores IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + InternalModerationCategoryScores IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeModerationCategoryScores(document.RootElement, options); + return DeserializeInternalModerationCategoryScores(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ModerationCategoryScores)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(InternalModerationCategoryScores)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationCategoryScores FromResponse(PipelineResponse response) + internal static InternalModerationCategoryScores FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationCategoryScores(document.RootElement); + return DeserializeInternalModerationCategoryScores(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/ModerationCategoryScores.cs b/src/Generated/Models/InternalModerationCategoryScores.cs similarity index 70% rename from src/Generated/Models/ModerationCategoryScores.cs rename to src/Generated/Models/InternalModerationCategoryScores.cs index a734260c..7c464556 100644 --- a/src/Generated/Models/ModerationCategoryScores.cs +++ b/src/Generated/Models/InternalModerationCategoryScores.cs @@ -7,10 +7,10 @@ namespace OpenAI.Moderations { - public partial class ModerationCategoryScores + internal partial class InternalModerationCategoryScores { internal IDictionary SerializedAdditionalRawData { get; set; } - internal ModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, float selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic) + internal InternalModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, float selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic) { Hate = hate; HateThreatening = hateThreatening; @@ -25,7 +25,7 @@ internal ModerationCategoryScores(float hate, float hateThreatening, float haras ViolenceGraphic = violenceGraphic; } - internal ModerationCategoryScores(float hate, float hateThreatening, float harassment, float harassmentThreatening, 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 selfHarm, float selfHarmIntent, float selfHarmInstructions, float sexual, float sexualMinors, float violence, float violenceGraphic, IDictionary serializedAdditionalRawData) { Hate = hate; HateThreatening = hateThreatening; @@ -41,7 +41,7 @@ internal ModerationCategoryScores(float hate, float hateThreatening, float haras SerializedAdditionalRawData = serializedAdditionalRawData; } - internal ModerationCategoryScores() + internal InternalModerationCategoryScores() { } diff --git a/src/Generated/Models/InternalUpload.Serialization.cs b/src/Generated/Models/InternalUpload.Serialization.cs index 6b2b8604..8f6ce8ce 100644 --- a/src/Generated/Models/InternalUpload.Serialization.cs +++ b/src/Generated/Models/InternalUpload.Serialization.cs @@ -123,7 +123,7 @@ internal static InternalUpload DeserializeInternalUpload(JsonElement element, Mo InternalUploadStatus status = default; DateTimeOffset expiresAt = default; InternalUploadObject? @object = default; - OpenAIFileInfo file = default; + OpenAIFile file = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -179,7 +179,7 @@ internal static InternalUpload DeserializeInternalUpload(JsonElement element, Mo file = null; continue; } - file = OpenAIFileInfo.DeserializeOpenAIFileInfo(property.Value, options); + file = OpenAIFile.DeserializeOpenAIFile(property.Value, options); continue; } if (true) diff --git a/src/Generated/Models/InternalUpload.cs b/src/Generated/Models/InternalUpload.cs index fb464ded..8e796539 100644 --- a/src/Generated/Models/InternalUpload.cs +++ b/src/Generated/Models/InternalUpload.cs @@ -25,7 +25,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, OpenAIFileInfo file, IDictionary serializedAdditionalRawData) + internal InternalUpload(string id, DateTimeOffset createdAt, string filename, int bytes, string purpose, InternalUploadStatus status, DateTimeOffset expiresAt, InternalUploadObject? @object, OpenAIFile file, IDictionary serializedAdditionalRawData) { Id = id; CreatedAt = createdAt; @@ -51,6 +51,6 @@ internal InternalUpload() public InternalUploadStatus Status { get; } public DateTimeOffset ExpiresAt { get; } public InternalUploadObject? Object { get; } - public OpenAIFileInfo File { get; } + public OpenAIFile File { get; } } } diff --git a/src/Generated/Models/ModerationResult.Serialization.cs b/src/Generated/Models/ModerationResult.Serialization.cs index 4e5f4ee2..f419fc8e 100644 --- a/src/Generated/Models/ModerationResult.Serialization.cs +++ b/src/Generated/Models/ModerationResult.Serialization.cs @@ -5,59 +5,12 @@ using System; using System.ClientModel; using System.ClientModel.Primitives; -using System.Collections.Generic; using System.Text.Json; namespace OpenAI.Moderations { public partial class ModerationResult : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ModerationResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("flagged") != true) - { - writer.WritePropertyName("flagged"u8); - writer.WriteBooleanValue(Flagged); - } - if (SerializedAdditionalRawData?.ContainsKey("categories") != true) - { - writer.WritePropertyName("categories"u8); - writer.WriteObjectValue(Categories, options); - } - if (SerializedAdditionalRawData?.ContainsKey("category_scores") != true) - { - writer.WritePropertyName("category_scores"u8); - writer.WriteObjectValue(CategoryScores, 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(); - } - ModerationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; @@ -70,46 +23,6 @@ ModerationResult IJsonModel.Create(ref Utf8JsonReader reader, return DeserializeModerationResult(document.RootElement, options); } - internal static ModerationResult DeserializeModerationResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool flagged = default; - ModerationCategories categories = default; - ModerationCategoryScores categoryScores = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("flagged"u8)) - { - flagged = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("categories"u8)) - { - categories = ModerationCategories.DeserializeModerationCategories(property.Value, options); - continue; - } - if (property.NameEquals("category_scores"u8)) - { - categoryScores = ModerationCategoryScores.DeserializeModerationCategoryScores(property.Value, options); - continue; - } - if (true) - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ModerationResult(flagged, categories, categoryScores, serializedAdditionalRawData); - } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; diff --git a/src/Generated/Models/ModerationResult.cs b/src/Generated/Models/ModerationResult.cs index ae015e2e..6361afdd 100644 --- a/src/Generated/Models/ModerationResult.cs +++ b/src/Generated/Models/ModerationResult.cs @@ -9,31 +9,5 @@ namespace OpenAI.Moderations { public partial class ModerationResult { - internal IDictionary SerializedAdditionalRawData { get; set; } - internal ModerationResult(bool flagged, ModerationCategories categories, ModerationCategoryScores categoryScores) - { - Argument.AssertNotNull(categories, nameof(categories)); - Argument.AssertNotNull(categoryScores, nameof(categoryScores)); - - Flagged = flagged; - Categories = categories; - CategoryScores = categoryScores; - } - - internal ModerationResult(bool flagged, ModerationCategories categories, ModerationCategoryScores categoryScores, IDictionary serializedAdditionalRawData) - { - Flagged = flagged; - Categories = categories; - CategoryScores = categoryScores; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - internal ModerationResult() - { - } - - public bool Flagged { get; } - public ModerationCategories Categories { get; } - public ModerationCategoryScores CategoryScores { get; } } } diff --git a/src/Generated/Models/ModerationResultCollection.Serialization.cs b/src/Generated/Models/ModerationResultCollection.Serialization.cs new file mode 100644 index 00000000..c0697ccd --- /dev/null +++ b/src/Generated/Models/ModerationResultCollection.Serialization.cs @@ -0,0 +1,68 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace OpenAI.Moderations +{ + public partial class ModerationResultCollection : IJsonModel + { + ModerationResultCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var 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); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var 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(ModerationResultCollection)} does not support writing '{options.Format}' format."); + } + } + + ModerationResultCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeModerationResultCollection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ModerationResultCollection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static ModerationResultCollection FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeModerationResultCollection(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/src/Generated/Models/ModerationCollection.cs b/src/Generated/Models/ModerationResultCollection.cs similarity index 73% rename from src/Generated/Models/ModerationCollection.cs rename to src/Generated/Models/ModerationResultCollection.cs index c8436d80..dd88f801 100644 --- a/src/Generated/Models/ModerationCollection.cs +++ b/src/Generated/Models/ModerationResultCollection.cs @@ -8,7 +8,7 @@ namespace OpenAI.Moderations { - public partial class ModerationCollection : ReadOnlyCollection + public partial class ModerationResultCollection : ReadOnlyCollection { public string Id { get; } public string Model { get; } diff --git a/src/Generated/Models/Embedding.Serialization.cs b/src/Generated/Models/OpenAIEmbedding.Serialization.cs similarity index 71% rename from src/Generated/Models/Embedding.Serialization.cs rename to src/Generated/Models/OpenAIEmbedding.Serialization.cs index 93a723fe..090448d7 100644 --- a/src/Generated/Models/Embedding.Serialization.cs +++ b/src/Generated/Models/OpenAIEmbedding.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Embeddings { - public partial class Embedding : IJsonModel + public partial class OpenAIEmbedding : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(Embedding)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbedding)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -65,19 +65,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteEndObject(); } - Embedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIEmbedding IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(Embedding)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbedding)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEmbedding(document.RootElement, options); + return DeserializeOpenAIEmbedding(document.RootElement, options); } - internal static Embedding DeserializeEmbedding(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIEmbedding DeserializeOpenAIEmbedding(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -114,44 +114,44 @@ internal static Embedding DeserializeEmbedding(JsonElement element, ModelReaderW } } serializedAdditionalRawData = rawDataDictionary; - return new Embedding(index, embedding, @object, serializedAdditionalRawData); + return new OpenAIEmbedding(index, embedding, @object, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(Embedding)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbedding)} does not support writing '{options.Format}' format."); } } - Embedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIEmbedding IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeEmbedding(document.RootElement, options); + return DeserializeOpenAIEmbedding(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(Embedding)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbedding)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static Embedding FromResponse(PipelineResponse response) + internal static OpenAIEmbedding FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeEmbedding(document.RootElement); + return DeserializeOpenAIEmbedding(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/Embedding.cs b/src/Generated/Models/OpenAIEmbedding.cs similarity index 78% rename from src/Generated/Models/Embedding.cs rename to src/Generated/Models/OpenAIEmbedding.cs index b8eb1097..a3b0b1aa 100644 --- a/src/Generated/Models/Embedding.cs +++ b/src/Generated/Models/OpenAIEmbedding.cs @@ -7,11 +7,11 @@ namespace OpenAI.Embeddings { - public partial class Embedding + public partial class OpenAIEmbedding { internal IDictionary SerializedAdditionalRawData { get; set; } - internal Embedding() + internal OpenAIEmbedding() { } diff --git a/src/Generated/Models/OpenAIModelInfoCollection.Serialization.cs b/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs similarity index 62% rename from src/Generated/Models/OpenAIModelInfoCollection.Serialization.cs rename to src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs index f9790a97..f025c25a 100644 --- a/src/Generated/Models/OpenAIModelInfoCollection.Serialization.cs +++ b/src/Generated/Models/OpenAIEmbeddingCollection.Serialization.cs @@ -7,57 +7,57 @@ using System.ClientModel.Primitives; using System.Text.Json; -namespace OpenAI.Models +namespace OpenAI.Embeddings { - public partial class OpenAIModelInfoCollection : IJsonModel + public partial class OpenAIEmbeddingCollection : IJsonModel { - OpenAIModelInfoCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIEmbeddingCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIModelInfoCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIModelInfoCollection(document.RootElement, options); + return DeserializeOpenAIEmbeddingCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(OpenAIModelInfoCollection)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support writing '{options.Format}' format."); } } - OpenAIModelInfoCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIEmbeddingCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIModelInfoCollection(document.RootElement, options); + return DeserializeOpenAIEmbeddingCollection(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(OpenAIModelInfoCollection)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIEmbeddingCollection)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIModelInfoCollection FromResponse(PipelineResponse response) + internal static OpenAIEmbeddingCollection FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIModelInfoCollection(document.RootElement); + return DeserializeOpenAIEmbeddingCollection(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/EmbeddingCollection.cs b/src/Generated/Models/OpenAIEmbeddingCollection.cs similarity index 74% rename from src/Generated/Models/EmbeddingCollection.cs rename to src/Generated/Models/OpenAIEmbeddingCollection.cs index 6afd1cf9..50b716a9 100644 --- a/src/Generated/Models/EmbeddingCollection.cs +++ b/src/Generated/Models/OpenAIEmbeddingCollection.cs @@ -8,7 +8,7 @@ namespace OpenAI.Embeddings { - public partial class EmbeddingCollection : ReadOnlyCollection + public partial class OpenAIEmbeddingCollection : ReadOnlyCollection { public string Model { get; } diff --git a/src/Generated/Models/OpenAIFileInfo.Serialization.cs b/src/Generated/Models/OpenAIFile.Serialization.cs similarity index 81% rename from src/Generated/Models/OpenAIFileInfo.Serialization.cs rename to src/Generated/Models/OpenAIFile.Serialization.cs index fcd6544a..ae2e64ee 100644 --- a/src/Generated/Models/OpenAIFileInfo.Serialization.cs +++ b/src/Generated/Models/OpenAIFile.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Files { - public partial class OpenAIFileInfo : IJsonModel + public partial class OpenAIFile : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIFileInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIFile)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -90,19 +90,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp writer.WriteEndObject(); } - OpenAIFileInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIFileInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIFileInfo(document.RootElement, options); + return DeserializeOpenAIFile(document.RootElement, options); } - internal static OpenAIFileInfo DeserializeOpenAIFileInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -174,7 +174,7 @@ internal static OpenAIFileInfo DeserializeOpenAIFileInfo(JsonElement element, Mo } } serializedAdditionalRawData = rawDataDictionary; - return new OpenAIFileInfo( + return new OpenAIFile( id, bytes, createdAt, @@ -186,41 +186,41 @@ internal static OpenAIFileInfo DeserializeOpenAIFileInfo(JsonElement element, Mo serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(OpenAIFileInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIFile)} does not support writing '{options.Format}' format."); } } - OpenAIFileInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIFileInfo(document.RootElement, options); + return DeserializeOpenAIFile(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(OpenAIFileInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIFileInfo FromResponse(PipelineResponse response) + internal static OpenAIFile FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIFileInfo(document.RootElement); + return DeserializeOpenAIFile(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/OpenAIFileInfo.cs b/src/Generated/Models/OpenAIFile.cs similarity index 68% rename from src/Generated/Models/OpenAIFileInfo.cs rename to src/Generated/Models/OpenAIFile.cs index 447da57d..1176232c 100644 --- a/src/Generated/Models/OpenAIFileInfo.cs +++ b/src/Generated/Models/OpenAIFile.cs @@ -7,10 +7,10 @@ namespace OpenAI.Files { - public partial class OpenAIFileInfo + public partial class OpenAIFile { internal IDictionary SerializedAdditionalRawData { get; set; } - internal OpenAIFileInfo(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, OpenAIFilePurpose purpose, OpenAIFileStatus status) + internal OpenAIFile(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, OpenAIFilePurpose purpose, OpenAIFileStatus status) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(filename, nameof(filename)); @@ -23,7 +23,7 @@ internal OpenAIFileInfo(string id, int? sizeInBytes, DateTimeOffset createdAt, s Status = status; } - internal OpenAIFileInfo(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, InternalOpenAIFileObject @object, OpenAIFilePurpose purpose, OpenAIFileStatus status, string statusDetails, IDictionary serializedAdditionalRawData) + internal OpenAIFile(string id, int? sizeInBytes, DateTimeOffset createdAt, string filename, InternalOpenAIFileObject @object, OpenAIFilePurpose purpose, OpenAIFileStatus status, string statusDetails, IDictionary serializedAdditionalRawData) { Id = id; SizeInBytes = sizeInBytes; @@ -36,7 +36,7 @@ internal OpenAIFileInfo(string id, int? sizeInBytes, DateTimeOffset createdAt, s SerializedAdditionalRawData = serializedAdditionalRawData; } - internal OpenAIFileInfo() + internal OpenAIFile() { } diff --git a/src/Generated/Models/ModerationCollection.Serialization.cs b/src/Generated/Models/OpenAIFileCollection.Serialization.cs similarity index 61% rename from src/Generated/Models/ModerationCollection.Serialization.cs rename to src/Generated/Models/OpenAIFileCollection.Serialization.cs index cb0f039f..5ed78de4 100644 --- a/src/Generated/Models/ModerationCollection.Serialization.cs +++ b/src/Generated/Models/OpenAIFileCollection.Serialization.cs @@ -7,57 +7,57 @@ using System.ClientModel.Primitives; using System.Text.Json; -namespace OpenAI.Moderations +namespace OpenAI.Files { - public partial class ModerationCollection : IJsonModel + public partial class OpenAIFileCollection : IJsonModel { - ModerationCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIFileCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ModerationCollection)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeModerationCollection(document.RootElement, options); + return DeserializeOpenAIFileCollection(document.RootElement, options); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(ModerationCollection)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support writing '{options.Format}' format."); } } - ModerationCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIFileCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeModerationCollection(document.RootElement, options); + return DeserializeOpenAIFileCollection(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ModerationCollection)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIFileCollection)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static ModerationCollection FromResponse(PipelineResponse response) + internal static OpenAIFileCollection FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeModerationCollection(document.RootElement); + return DeserializeOpenAIFileCollection(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/OpenAIFileInfoCollection.cs b/src/Generated/Models/OpenAIFileCollection.cs similarity index 66% rename from src/Generated/Models/OpenAIFileInfoCollection.cs rename to src/Generated/Models/OpenAIFileCollection.cs index c1887f23..b868860e 100644 --- a/src/Generated/Models/OpenAIFileInfoCollection.cs +++ b/src/Generated/Models/OpenAIFileCollection.cs @@ -8,7 +8,7 @@ namespace OpenAI.Files { - public partial class OpenAIFileInfoCollection : ReadOnlyCollection + public partial class OpenAIFileCollection : ReadOnlyCollection { } } diff --git a/src/Generated/Models/OpenAIFileInfoCollection.Serialization.cs b/src/Generated/Models/OpenAIFileInfoCollection.Serialization.cs deleted file mode 100644 index 5cd5d039..00000000 --- a/src/Generated/Models/OpenAIFileInfoCollection.Serialization.cs +++ /dev/null @@ -1,68 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace OpenAI.Files -{ - public partial class OpenAIFileInfoCollection : IJsonModel - { - OpenAIFileInfoCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(OpenAIFileInfoCollection)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIFileInfoCollection(document.RootElement, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var 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(OpenAIFileInfoCollection)} does not support writing '{options.Format}' format."); - } - } - - OpenAIFileInfoCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIFileInfoCollection(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(OpenAIFileInfoCollection)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal static OpenAIFileInfoCollection FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIFileInfoCollection(document.RootElement); - } - - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/src/Generated/Models/OpenAIModelInfo.Serialization.cs b/src/Generated/Models/OpenAIModel.Serialization.cs similarity index 74% rename from src/Generated/Models/OpenAIModelInfo.Serialization.cs rename to src/Generated/Models/OpenAIModel.Serialization.cs index 575c7e96..4d230a10 100644 --- a/src/Generated/Models/OpenAIModelInfo.Serialization.cs +++ b/src/Generated/Models/OpenAIModel.Serialization.cs @@ -10,14 +10,14 @@ namespace OpenAI.Models { - public partial class OpenAIModelInfo : IJsonModel + public partial class OpenAIModel : IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIModelInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIModel)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -63,19 +63,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO writer.WriteEndObject(); } - OpenAIModelInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(OpenAIModelInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIModel)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOpenAIModelInfo(document.RootElement, options); + return DeserializeOpenAIModel(document.RootElement, options); } - internal static OpenAIModelInfo DeserializeOpenAIModelInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIModel DeserializeOpenAIModel(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -118,44 +118,44 @@ internal static OpenAIModelInfo DeserializeOpenAIModelInfo(JsonElement element, } } serializedAdditionalRawData = rawDataDictionary; - return new OpenAIModelInfo(id, created, @object, ownedBy, serializedAdditionalRawData); + return new OpenAIModel(id, created, @object, ownedBy, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var 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(OpenAIModelInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIModel)} does not support writing '{options.Format}' format."); } } - OpenAIModelInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data); - return DeserializeOpenAIModelInfo(document.RootElement, options); + return DeserializeOpenAIModel(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(OpenAIModelInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIModel)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - internal static OpenAIModelInfo FromResponse(PipelineResponse response) + internal static OpenAIModel FromResponse(PipelineResponse response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeOpenAIModelInfo(document.RootElement); + return DeserializeOpenAIModel(document.RootElement); } internal virtual BinaryContent ToBinaryContent() diff --git a/src/Generated/Models/OpenAIModelInfo.cs b/src/Generated/Models/OpenAIModel.cs similarity index 68% rename from src/Generated/Models/OpenAIModelInfo.cs rename to src/Generated/Models/OpenAIModel.cs index c838e75a..390f591e 100644 --- a/src/Generated/Models/OpenAIModelInfo.cs +++ b/src/Generated/Models/OpenAIModel.cs @@ -7,10 +7,10 @@ namespace OpenAI.Models { - public partial class OpenAIModelInfo + public partial class OpenAIModel { internal IDictionary SerializedAdditionalRawData { get; set; } - internal OpenAIModelInfo(string id, DateTimeOffset createdAt, string ownedBy) + internal OpenAIModel(string id, DateTimeOffset createdAt, string ownedBy) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(ownedBy, nameof(ownedBy)); @@ -20,7 +20,7 @@ internal OpenAIModelInfo(string id, DateTimeOffset createdAt, string ownedBy) OwnedBy = ownedBy; } - internal OpenAIModelInfo(string id, DateTimeOffset createdAt, InternalModelObject @object, string ownedBy, IDictionary serializedAdditionalRawData) + internal OpenAIModel(string id, DateTimeOffset createdAt, InternalModelObject @object, string ownedBy, IDictionary serializedAdditionalRawData) { Id = id; CreatedAt = createdAt; @@ -29,7 +29,7 @@ internal OpenAIModelInfo(string id, DateTimeOffset createdAt, InternalModelObjec SerializedAdditionalRawData = serializedAdditionalRawData; } - internal OpenAIModelInfo() + internal OpenAIModel() { } diff --git a/src/Generated/Models/OpenAIModelCollection.Serialization.cs b/src/Generated/Models/OpenAIModelCollection.Serialization.cs new file mode 100644 index 00000000..0d8747b0 --- /dev/null +++ b/src/Generated/Models/OpenAIModelCollection.Serialization.cs @@ -0,0 +1,68 @@ +// + +#nullable disable + +using System; +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace OpenAI.Models +{ + public partial class OpenAIModelCollection : IJsonModel + { + OpenAIModelCollection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var 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); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var 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(OpenAIModelCollection)} does not support writing '{options.Format}' format."); + } + } + + OpenAIModelCollection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeOpenAIModelCollection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAIModelCollection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + internal static OpenAIModelCollection FromResponse(PipelineResponse response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIModelCollection(document.RootElement); + } + + internal virtual BinaryContent ToBinaryContent() + { + return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + } + } +} diff --git a/src/Generated/Models/OpenAIModelInfoCollection.cs b/src/Generated/Models/OpenAIModelCollection.cs similarity index 66% rename from src/Generated/Models/OpenAIModelInfoCollection.cs rename to src/Generated/Models/OpenAIModelCollection.cs index f917c20d..08dc52d8 100644 --- a/src/Generated/Models/OpenAIModelInfoCollection.cs +++ b/src/Generated/Models/OpenAIModelCollection.cs @@ -8,7 +8,7 @@ namespace OpenAI.Models { - public partial class OpenAIModelInfoCollection : ReadOnlyCollection + public partial class OpenAIModelCollection : ReadOnlyCollection { } } diff --git a/src/Generated/Models/RunCreationOptions.Serialization.cs b/src/Generated/Models/RunCreationOptions.Serialization.cs index 2c0dc45c..1e534942 100644 --- a/src/Generated/Models/RunCreationOptions.Serialization.cs +++ b/src/Generated/Models/RunCreationOptions.Serialization.cs @@ -198,10 +198,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNull("tool_choice"); } } - if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(ParallelToolCallsEnabled)) + if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true && Optional.IsDefined(AllowParallelToolCalls)) { writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(ParallelToolCallsEnabled.Value); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); } if (SerializedAdditionalRawData?.ContainsKey("response_format") != true && Optional.IsDefined(ResponseFormat)) { diff --git a/src/Generated/Models/RunCreationOptions.cs b/src/Generated/Models/RunCreationOptions.cs index 9e0d88fa..7205b3c9 100644 --- a/src/Generated/Models/RunCreationOptions.cs +++ b/src/Generated/Models/RunCreationOptions.cs @@ -11,7 +11,7 @@ public partial class RunCreationOptions { internal IDictionary SerializedAdditionalRawData { get; set; } - internal RunCreationOptions(string assistantId, string modelOverride, string instructionsOverride, string additionalInstructions, IList internalMessages, IList toolsOverride, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, bool? stream, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? parallelToolCallsEnabled, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + internal RunCreationOptions(string assistantId, string modelOverride, string instructionsOverride, string additionalInstructions, IList internalMessages, IList toolsOverride, IDictionary metadata, float? temperature, float? nucleusSamplingFactor, bool? stream, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) { AssistantId = assistantId; ModelOverride = modelOverride; @@ -27,7 +27,7 @@ internal RunCreationOptions(string assistantId, string modelOverride, string ins MaxCompletionTokens = maxCompletionTokens; TruncationStrategy = truncationStrategy; ToolConstraint = toolConstraint; - ParallelToolCallsEnabled = parallelToolCallsEnabled; + AllowParallelToolCalls = allowParallelToolCalls; ResponseFormat = responseFormat; SerializedAdditionalRawData = serializedAdditionalRawData; } diff --git a/src/Generated/Models/RunTokenUsage.Serialization.cs b/src/Generated/Models/RunTokenUsage.Serialization.cs index 7f50758c..bd60e19a 100644 --- a/src/Generated/Models/RunTokenUsage.Serialization.cs +++ b/src/Generated/Models/RunTokenUsage.Serialization.cs @@ -24,17 +24,17 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt if (SerializedAdditionalRawData?.ContainsKey("completion_tokens") != true) { writer.WritePropertyName("completion_tokens"u8); - writer.WriteNumberValue(CompletionTokens); + writer.WriteNumberValue(OutputTokenCount); } if (SerializedAdditionalRawData?.ContainsKey("prompt_tokens") != true) { writer.WritePropertyName("prompt_tokens"u8); - writer.WriteNumberValue(PromptTokens); + writer.WriteNumberValue(InputTokenCount); } if (SerializedAdditionalRawData?.ContainsKey("total_tokens") != true) { writer.WritePropertyName("total_tokens"u8); - writer.WriteNumberValue(TotalTokens); + writer.WriteNumberValue(TotalTokenCount); } if (SerializedAdditionalRawData != null) { diff --git a/src/Generated/Models/RunTokenUsage.cs b/src/Generated/Models/RunTokenUsage.cs index c961964d..fce72983 100644 --- a/src/Generated/Models/RunTokenUsage.cs +++ b/src/Generated/Models/RunTokenUsage.cs @@ -10,27 +10,23 @@ namespace OpenAI.Assistants public partial class RunTokenUsage { internal IDictionary SerializedAdditionalRawData { get; set; } - internal RunTokenUsage(int completionTokens, int promptTokens, int totalTokens) + internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount) { - CompletionTokens = completionTokens; - PromptTokens = promptTokens; - TotalTokens = totalTokens; + OutputTokenCount = outputTokenCount; + InputTokenCount = inputTokenCount; + TotalTokenCount = totalTokenCount; } - internal RunTokenUsage(int completionTokens, int promptTokens, int totalTokens, IDictionary serializedAdditionalRawData) + internal RunTokenUsage(int outputTokenCount, int inputTokenCount, int totalTokenCount, IDictionary serializedAdditionalRawData) { - CompletionTokens = completionTokens; - PromptTokens = promptTokens; - TotalTokens = totalTokens; + OutputTokenCount = outputTokenCount; + InputTokenCount = inputTokenCount; + TotalTokenCount = totalTokenCount; SerializedAdditionalRawData = serializedAdditionalRawData; } internal RunTokenUsage() { } - - public int CompletionTokens { get; } - public int PromptTokens { get; } - public int TotalTokens { get; } } } diff --git a/src/Generated/Models/ThreadRun.Serialization.cs b/src/Generated/Models/ThreadRun.Serialization.cs index 4c884489..6f264303 100644 --- a/src/Generated/Models/ThreadRun.Serialization.cs +++ b/src/Generated/Models/ThreadRun.Serialization.cs @@ -272,7 +272,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions if (SerializedAdditionalRawData?.ContainsKey("parallel_tool_calls") != true) { writer.WritePropertyName("parallel_tool_calls"u8); - writer.WriteBooleanValue(ParallelToolCallsEnabled.Value); + writer.WriteBooleanValue(AllowParallelToolCalls.Value); } if (SerializedAdditionalRawData?.ContainsKey("response_format") != true) { diff --git a/src/Generated/Models/ThreadRun.cs b/src/Generated/Models/ThreadRun.cs index cc4a4457..f1998480 100644 --- a/src/Generated/Models/ThreadRun.cs +++ b/src/Generated/Models/ThreadRun.cs @@ -12,7 +12,7 @@ public partial class ThreadRun { internal IDictionary SerializedAdditionalRawData { get; set; } - 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? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? parallelToolCallsEnabled, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) + 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? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -39,7 +39,7 @@ internal ThreadRun(string id, InternalRunObjectObject @object, DateTimeOffset cr MaxCompletionTokens = maxCompletionTokens; TruncationStrategy = truncationStrategy; ToolConstraint = toolConstraint; - ParallelToolCallsEnabled = parallelToolCallsEnabled; + AllowParallelToolCalls = allowParallelToolCalls; ResponseFormat = responseFormat; SerializedAdditionalRawData = serializedAdditionalRawData; } diff --git a/src/Generated/OpenAIModelFactory.cs b/src/Generated/OpenAIModelFactory.cs index 68a9674f..50039e67 100644 --- a/src/Generated/OpenAIModelFactory.cs +++ b/src/Generated/OpenAIModelFactory.cs @@ -43,9 +43,9 @@ public static RunIncompleteDetails RunIncompleteDetails(RunIncompleteReason? rea return new RunIncompleteDetails(reason, serializedAdditionalRawData: null); } - public static RunTokenUsage RunTokenUsage(int completionTokens = default, int promptTokens = default, int totalTokens = default) + public static RunTokenUsage RunTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default) { - return new RunTokenUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); + return new RunTokenUsage(outputTokenCount, inputTokenCount, totalTokenCount, serializedAdditionalRawData: null); } public static RunStepError RunStepError(RunStepErrorCode code = default, string message = null) @@ -58,50 +58,11 @@ public static RunStepTokenUsage RunStepTokenUsage(int completionTokens = default return new RunStepTokenUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); } - public static ModerationCollection ModerationCollection(string id = null, string model = null, IEnumerable results = null) + public static ModerationResultCollection ModerationResultCollection(string id = null, string model = null, IEnumerable results = null) { results ??= new List(); - return new ModerationCollection(id, model, results?.ToList()); - } - - public static ModerationResult ModerationResult(bool flagged = default, ModerationCategories categories = null, ModerationCategoryScores categoryScores = null) - { - return new ModerationResult(flagged, categories, categoryScores, serializedAdditionalRawData: null); - } - - public static ModerationCategories ModerationCategories(bool hate = default, bool hateThreatening = default, bool harassment = default, bool harassmentThreatening = default, bool selfHarm = default, bool selfHarmIntent = default, bool selfHarmInstructions = default, bool sexual = default, bool sexualMinors = default, bool violence = default, bool violenceGraphic = default) - { - return new ModerationCategories( - hate, - hateThreatening, - harassment, - harassmentThreatening, - selfHarm, - selfHarmIntent, - selfHarmInstructions, - sexual, - sexualMinors, - violence, - violenceGraphic, - serializedAdditionalRawData: null); - } - - public static ModerationCategoryScores ModerationCategoryScores(float hate = default, float hateThreatening = default, float harassment = default, float harassmentThreatening = default, float selfHarm = default, float selfHarmIntent = default, float selfHarmInstructions = default, float sexual = default, float sexualMinors = default, float violence = default, float violenceGraphic = default) - { - return new ModerationCategoryScores( - hate, - hateThreatening, - harassment, - harassmentThreatening, - selfHarm, - selfHarmIntent, - selfHarmInstructions, - sexual, - sexualMinors, - violence, - violenceGraphic, - serializedAdditionalRawData: null); + return new ModerationResultCollection(id, model, results?.ToList()); } public static MessageFailureDetails MessageFailureDetails(MessageFailureReason reason = default) @@ -121,9 +82,9 @@ public static GeneratedImage GeneratedImage(BinaryData imageBytes = null, Uri im return new GeneratedImage(imageBytes, imageUri, revisedPrompt, serializedAdditionalRawData: null); } - public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokens = default, int totalTokens = default) + public static EmbeddingTokenUsage EmbeddingTokenUsage(int inputTokenCount = default, int totalTokenCount = default) { - return new EmbeddingTokenUsage(inputTokens, totalTokens, serializedAdditionalRawData: null); + return new EmbeddingTokenUsage(inputTokenCount, totalTokenCount, serializedAdditionalRawData: null); } public static ChatTokenUsage ChatTokenUsage(int outputTokenCount = default, int inputTokenCount = default, int totalTokenCount = default, ChatOutputTokenUsageDetails outputTokenDetails = null) diff --git a/tests/Assistants/Assistants.VectorStoresTests.cs b/tests/Assistants/Assistants.VectorStoresTests.cs index eecc3b4d..126b6978 100644 --- a/tests/Assistants/Assistants.VectorStoresTests.cs +++ b/tests/Assistants/Assistants.VectorStoresTests.cs @@ -23,7 +23,7 @@ public class VectorStoresTests : SyncAsyncTestBase { private readonly List _jobsToCancel = []; private readonly List _associationsToRemove = []; - private readonly List _filesToDelete = []; + private readonly List _filesToDelete = []; private readonly List _vectorStoresToDelete = []; private static readonly DateTimeOffset s_2024 = new(2024, 1, 1, 0, 0, 0, TimeSpan.Zero); @@ -51,7 +51,7 @@ public async Task CanCreateGetAndDeleteVectorStores() Assert.That(deletionResult.Deleted, Is.True); _vectorStoresToDelete.RemoveAt(_vectorStoresToDelete.Count - 1); - IReadOnlyList testFiles = GetNewTestFiles(5); + IReadOnlyList testFiles = GetNewTestFiles(5); VectorStoreCreationOptions creationOptions = new VectorStoreCreationOptions() { FileIds = { testFiles[0].Id }, @@ -205,9 +205,9 @@ public async Task CanAssociateFiles() VectorStore vectorStore = client.CreateVectorStore(); Validate(vectorStore); - IReadOnlyList files = GetNewTestFiles(3); + IReadOnlyList files = GetNewTestFiles(3); - foreach (OpenAIFileInfo file in files) + foreach (OpenAIFile file in files) { VectorStoreFileAssociation association = IsAsync ? await client.AddFileToVectorStoreAsync(vectorStore, file) @@ -265,9 +265,9 @@ public async Task Pagination_CanRehydrateFileAssociationCollectionAsync() VectorStore vectorStore = client.CreateVectorStore(); Validate(vectorStore); - IReadOnlyList files = GetNewTestFiles(6); + IReadOnlyList files = GetNewTestFiles(6); - foreach (OpenAIFileInfo file in files) + foreach (OpenAIFile file in files) { VectorStoreFileAssociation association = client.AddFileToVectorStore(vectorStore, file); Validate(association); @@ -345,9 +345,9 @@ public void Pagination_CanRehydrateFileAssociationCollection() VectorStore vectorStore = client.CreateVectorStore(); Validate(vectorStore); - IReadOnlyList files = GetNewTestFiles(6); + IReadOnlyList files = GetNewTestFiles(6); - foreach (OpenAIFileInfo file in files) + foreach (OpenAIFile file in files) { VectorStoreFileAssociation association = client.AddFileToVectorStore(vectorStore, file); Validate(association); @@ -427,7 +427,7 @@ public async Task CanUseBatchIngestion() VectorStore vectorStore = client.CreateVectorStore(); Validate(vectorStore); - IReadOnlyList testFiles = GetNewTestFiles(5); + IReadOnlyList testFiles = GetNewTestFiles(5); VectorStoreBatchFileJob batchJob = client.CreateBatchFileJob(vectorStore, testFiles); Validate(batchJob); @@ -483,7 +483,7 @@ public enum ChunkingStrategyKind { Auto, Static } [TestCase(ChunkingStrategyKind.Static)] public async Task CanApplyChunkingStrategy(ChunkingStrategyKind strategyKind) { - IReadOnlyList testFiles = GetNewTestFiles(5); + IReadOnlyList testFiles = GetNewTestFiles(5); VectorStoreClient client = GetTestClient(); @@ -565,14 +565,14 @@ public async Task CanApplyChunkingStrategy(ChunkingStrategyKind strategyKind) } } - private IReadOnlyList GetNewTestFiles(int count) + private IReadOnlyList GetNewTestFiles(int count) { - List files = []; + List files = []; FileClient client = GetTestClient(TestScenario.Files); for (int i = 0; i < count; i++) { - OpenAIFileInfo file = client.UploadFile( + OpenAIFile file = client.UploadFile( BinaryData.FromString("This is a test file").ToStream(), $"test_file_{i.ToString().PadLeft(3, '0')}.txt", FileUploadPurpose.Assistants); @@ -602,7 +602,7 @@ protected void Cleanup() ClientResult protocolResult = vectorStoreClient.RemoveFileFromStore(association.VectorStoreId, association.FileId, requestOptions); Console.WriteLine($"Cleanup: {association.FileId}<->{association.VectorStoreId} => {protocolResult?.GetRawResponse()?.Status}"); } - foreach (OpenAIFileInfo file in _filesToDelete) + foreach (OpenAIFile file in _filesToDelete) { Console.WriteLine($"Cleanup: {file.Id} -> {fileClient.DeleteFile(file.Id, requestOptions)?.GetRawResponse()?.Status}"); } @@ -634,7 +634,7 @@ private void Validate(T target) Assert.That(association?.VectorStoreId, Is.Not.Null); _associationsToRemove.Add(association); } - else if (target is OpenAIFileInfo file) + else if (target is OpenAIFile file) { Assert.That(file?.Id, Is.Not.Null); _filesToDelete.Add(file); diff --git a/tests/Assistants/AssistantsTests.cs b/tests/Assistants/AssistantsTests.cs index b00c7bdf..c22a6e97 100644 --- a/tests/Assistants/AssistantsTests.cs +++ b/tests/Assistants/AssistantsTests.cs @@ -26,7 +26,7 @@ public class AssistantsTests : SyncAsyncTestBase private readonly List _assistantsToDelete = []; private readonly List _threadsToDelete = []; private readonly List _messagesToDelete = []; - private readonly List _filesToDelete = []; + private readonly List _filesToDelete = []; private readonly List _vectorStoreIdsToDelete = []; private static readonly DateTimeOffset s_2024 = new(2024, 1, 1, 0, 0, 0, TimeSpan.Zero); @@ -68,7 +68,7 @@ protected void Cleanup() { Console.WriteLine($"Cleanup: {thread.Id} -> {client.DeleteThread(thread.Id, requestOptions)?.GetRawResponse().Status}"); } - foreach (OpenAIFileInfo file in _filesToDelete) + foreach (OpenAIFile file in _filesToDelete) { Console.WriteLine($"Cleanup: {file.Id} -> {fileClient.DeleteFile(file.Id, requestOptions)?.GetRawResponse().Status}"); } @@ -272,7 +272,7 @@ public async Task ThreadWithInitialMessagesWorks() MessageRole.User, [ "Can you describe this image for me?", - MessageContent.FromImageUrl(new Uri("https://test.openai.com/image.png")) + MessageContent.FromImageUri(new Uri("https://test.openai.com/image.png")) ]) { Metadata = @@ -298,7 +298,7 @@ public async Task ThreadWithInitialMessagesWorks() Assert.That(messages[1].Content[0], Is.Not.Null); Assert.That(messages[1].Content[0].Text, Is.EqualTo("Can you describe this image for me?")); Assert.That(messages[1].Content[1], Is.Not.Null); - Assert.That(messages[1].Content[1].ImageUrl.AbsoluteUri, Is.EqualTo("https://test.openai.com/image.png")); + Assert.That(messages[1].Content[1].ImageUri.AbsoluteUri, Is.EqualTo("https://test.openai.com/image.png")); } [Test] @@ -371,7 +371,7 @@ public async Task BasicRunStepFunctionalityWorks() Validate(assistant); FileClient fileClient = GetTestClient(TestScenario.Files); - OpenAIFileInfo equationFile = fileClient.UploadFile( + OpenAIFile equationFile = fileClient.UploadFile( BinaryData.FromString(""" x,y 2,5 @@ -409,7 +409,7 @@ public async Task BasicRunStepFunctionalityWorks() run = client.GetRun(run); } Assert.That(run.Status, Is.EqualTo(RunStatus.Completed)); - Assert.That(run.Usage?.TotalTokens, Is.GreaterThan(0)); + Assert.That(run.Usage?.TotalTokenCount, Is.GreaterThan(0)); List runSteps = IsAsync ? await client.GetRunStepsAsync(run).ToListAsync() @@ -793,7 +793,7 @@ public async Task FileSearchWorks() { // First, we need to upload a simple test file. FileClient fileClient = GetTestClient(TestScenario.Files); - OpenAIFileInfo testFile = fileClient.UploadFile( + OpenAIFile testFile = fileClient.UploadFile( BinaryData.FromString(""" This file describes the favorite foods of several people. @@ -972,7 +972,7 @@ public async Task BasicFileSearchStreamingWorks() AssistantClient client = GetTestClient(TestScenario.Assistants); // First, upload a simple test file. - OpenAIFileInfo testFile = fileClient.UploadFile(BinaryData.FromString(fileContent), fileName, FileUploadPurpose.Assistants); + OpenAIFile testFile = fileClient.UploadFile(BinaryData.FromString(fileContent), fileName, FileUploadPurpose.Assistants); Validate(testFile); // Create an assistant, using the creation helper to make a new vector store. @@ -1657,7 +1657,7 @@ public async Task Pagination_CanRehydrateRunStepPageCollectionFromBytesAsync() Validate(assistant); FileClient fileClient = GetTestClient(TestScenario.Files); - OpenAIFileInfo equationFile = fileClient.UploadFile( + OpenAIFile equationFile = fileClient.UploadFile( BinaryData.FromString(""" x,y 2,5 @@ -1695,7 +1695,7 @@ public async Task Pagination_CanRehydrateRunStepPageCollectionFromBytesAsync() run = client.GetRun(run); } Assert.That(run.Status, Is.EqualTo(RunStatus.Completed)); - Assert.That(run.Usage?.TotalTokens, Is.GreaterThan(0)); + Assert.That(run.Usage?.TotalTokenCount, Is.GreaterThan(0)); IReadOnlyList runSteps; IReadOnlyList rehydratedRunSteps; @@ -1732,7 +1732,7 @@ public void Pagination_CanRehydrateRunStepPageCollectionFromBytes() Validate(assistant); FileClient fileClient = GetTestClient(TestScenario.Files); - OpenAIFileInfo equationFile = fileClient.UploadFile( + OpenAIFile equationFile = fileClient.UploadFile( BinaryData.FromString(""" x,y 2,5 @@ -1770,7 +1770,7 @@ public void Pagination_CanRehydrateRunStepPageCollectionFromBytes() run = client.GetRun(run); } Assert.That(run.Status, Is.EqualTo(RunStatus.Completed)); - Assert.That(run.Usage?.TotalTokens, Is.GreaterThan(0)); + Assert.That(run.Usage?.TotalTokenCount, Is.GreaterThan(0)); IReadOnlyList runSteps; IReadOnlyList rehydratedRunSteps; @@ -1885,7 +1885,7 @@ private void Validate(T target) { Assert.That(run?.Id, Is.Not.Null); } - else if (target is OpenAIFileInfo file) + else if (target is OpenAIFile file) { Assert.That(file?.Id, Is.Not.Null); _filesToDelete.Add(file); diff --git a/tests/Batch/BatchTests.cs b/tests/Batch/BatchTests.cs index b6d28cc9..1eea2986 100644 --- a/tests/Batch/BatchTests.cs +++ b/tests/Batch/BatchTests.cs @@ -107,7 +107,7 @@ public async Task CreateGetAndCancelBatchProtocol() testFileStream.Position = 0; FileClient fileClient = GetTestClient(TestScenario.Files); - OpenAIFileInfo inputFile = await fileClient.UploadFileAsync(testFileStream, "test-batch-file", FileUploadPurpose.Batch); + OpenAIFile inputFile = await fileClient.UploadFileAsync(testFileStream, "test-batch-file", FileUploadPurpose.Batch); Assert.That(inputFile.Id, Is.Not.Null.And.Not.Empty); BatchClient client = GetTestClient(); diff --git a/tests/Embeddings/EmbeddingsMockTests.cs b/tests/Embeddings/EmbeddingsMockTests.cs index 21994213..3f478a04 100644 --- a/tests/Embeddings/EmbeddingsMockTests.cs +++ b/tests/Embeddings/EmbeddingsMockTests.cs @@ -42,7 +42,7 @@ public async Task GenerateEmbeddingDeserializesVector() """); EmbeddingClient client = new EmbeddingClient("model", s_fakeCredential, clientOptions); - Embedding embedding = IsAsync + OpenAIEmbedding embedding = IsAsync ? await client.GenerateEmbeddingAsync("prompt") : client.GenerateEmbedding("prompt"); @@ -83,12 +83,12 @@ public async Task GenerateEmbeddingsWithStringsDeserializesUsage() """); EmbeddingClient client = new EmbeddingClient("model", s_fakeCredential, clientOptions); - EmbeddingCollection embeddings = IsAsync + OpenAIEmbeddingCollection embeddings = IsAsync ? await client.GenerateEmbeddingsAsync(["prompt"]) : client.GenerateEmbeddings(["prompt"]); - Assert.That(embeddings.Usage.InputTokens, Is.EqualTo(10)); - Assert.That(embeddings.Usage.TotalTokens, Is.EqualTo(20)); + Assert.That(embeddings.Usage.InputTokenCount, Is.EqualTo(10)); + Assert.That(embeddings.Usage.TotalTokenCount, Is.EqualTo(20)); } [Test] @@ -110,10 +110,10 @@ public async Task GenerateEmbeddingsWithStringsDeserializesVector() """); EmbeddingClient client = new EmbeddingClient("model", s_fakeCredential, clientOptions); - EmbeddingCollection embeddings = IsAsync + OpenAIEmbeddingCollection embeddings = IsAsync ? await client.GenerateEmbeddingsAsync(["prompt"]) : client.GenerateEmbeddings(["prompt"]); - Embedding embedding = embeddings.Single(); + OpenAIEmbedding embedding = embeddings.Single(); float[] vector = embedding.ToFloats().ToArray(); Assert.That(vector.SequenceEqual([1f, 2f, 3f])); @@ -152,12 +152,12 @@ public async Task GenerateEmbeddingsWithIntegersDeserializesUsage() """); EmbeddingClient client = new EmbeddingClient("model", s_fakeCredential, clientOptions); - EmbeddingCollection embeddings = IsAsync + OpenAIEmbeddingCollection embeddings = IsAsync ? await client.GenerateEmbeddingsAsync([[1]]) : client.GenerateEmbeddings([[1]]); - Assert.That(embeddings.Usage.InputTokens, Is.EqualTo(10)); - Assert.That(embeddings.Usage.TotalTokens, Is.EqualTo(20)); + Assert.That(embeddings.Usage.InputTokenCount, Is.EqualTo(10)); + Assert.That(embeddings.Usage.TotalTokenCount, Is.EqualTo(20)); } [Test] @@ -179,10 +179,10 @@ public async Task GenerateEmbeddingsWithIntegersDeserializesVector() """); EmbeddingClient client = new EmbeddingClient("model", s_fakeCredential, clientOptions); - EmbeddingCollection embeddings = IsAsync + OpenAIEmbeddingCollection embeddings = IsAsync ? await client.GenerateEmbeddingsAsync([[1]]) : client.GenerateEmbeddings([[1]]); - Embedding embedding = embeddings.Single(); + OpenAIEmbedding embedding = embeddings.Single(); float[] vector = embedding.ToFloats().ToArray(); Assert.That(vector.SequenceEqual([1f, 2f, 3f])); diff --git a/tests/Embeddings/EmbeddingsTests.cs b/tests/Embeddings/EmbeddingsTests.cs index 18a40650..02ab9d33 100644 --- a/tests/Embeddings/EmbeddingsTests.cs +++ b/tests/Embeddings/EmbeddingsTests.cs @@ -34,7 +34,7 @@ public async Task GenerateSingleEmbedding() string input = "Hello, world!"; - Embedding embedding = IsAsync + OpenAIEmbedding embedding = IsAsync ? await client.GenerateEmbeddingAsync(input) : client.GenerateEmbedding(input); Assert.That(embedding, Is.Not.Null); @@ -62,7 +62,7 @@ public async Task GenerateMultipleEmbeddings(EmbeddingsInputKind embeddingsInput Dimensions = Dimensions, }; - EmbeddingCollection embeddings = null; + OpenAIEmbeddingCollection embeddings = null; if (embeddingsInputKind == EmbeddingsInputKind.UsingStrings) { @@ -94,8 +94,8 @@ public async Task GenerateMultipleEmbeddings(EmbeddingsInputKind embeddingsInput Assert.That(embeddings, Is.Not.Null); Assert.That(embeddings.Count, Is.EqualTo(3)); Assert.That(embeddings.Model, Is.EqualTo("text-embedding-3-small")); - Assert.That(embeddings.Usage.InputTokens, Is.GreaterThan(0)); - Assert.That(embeddings.Usage.TotalTokens, Is.GreaterThan(0)); + Assert.That(embeddings.Usage.InputTokenCount, Is.GreaterThan(0)); + Assert.That(embeddings.Usage.TotalTokenCount, Is.GreaterThan(0)); for (int i = 0; i < embeddings.Count; i++) { diff --git a/tests/Embeddings/OpenAIEmbeddingsModelFactoryTests.cs b/tests/Embeddings/OpenAIEmbeddingsModelFactoryTests.cs index 44c65f57..a9a38a25 100644 --- a/tests/Embeddings/OpenAIEmbeddingsModelFactoryTests.cs +++ b/tests/Embeddings/OpenAIEmbeddingsModelFactoryTests.cs @@ -13,7 +13,7 @@ public class OpenAIEmbeddingsModelFactoryTests [Test] public void EmbeddingWithNoPropertiesWorks() { - Embedding embedding = OpenAIEmbeddingsModelFactory.Embedding(); + OpenAIEmbedding embedding = OpenAIEmbeddingsModelFactory.OpenAIEmbedding(); Assert.That(embedding.Index, Is.EqualTo(default(int))); Assert.That(embedding.ToFloats().ToArray(), Is.Not.Null.And.Empty); @@ -23,7 +23,7 @@ public void EmbeddingWithNoPropertiesWorks() public void EmbeddingWithIndexWorks() { int index = 10; - Embedding embedding = OpenAIEmbeddingsModelFactory.Embedding(index: index); + OpenAIEmbedding embedding = OpenAIEmbeddingsModelFactory.OpenAIEmbedding(index: index); Assert.That(embedding.Index, Is.EqualTo(index)); Assert.That(embedding.ToFloats().ToArray(), Is.Not.Null.And.Empty); @@ -33,7 +33,7 @@ public void EmbeddingWithIndexWorks() public void EmbeddingWithVectorWorks() { IEnumerable vector = [1f, 2f, 3f]; - Embedding embedding = OpenAIEmbeddingsModelFactory.Embedding(vector: vector); + OpenAIEmbedding embedding = OpenAIEmbeddingsModelFactory.OpenAIEmbedding(vector: vector); Assert.That(embedding.Index, Is.EqualTo(default(int))); Assert.That(embedding.ToFloats().ToArray().SequenceEqual(vector), Is.True); @@ -42,7 +42,7 @@ public void EmbeddingWithVectorWorks() [Test] public void EmbeddingCollectionWithNoPropertiesWorks() { - EmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.EmbeddingCollection(); + OpenAIEmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.OpenAIEmbeddingCollection(); Assert.That(embeddingCollection.Count, Is.EqualTo(0)); Assert.That(embeddingCollection.Model, Is.Null); @@ -52,11 +52,11 @@ public void EmbeddingCollectionWithNoPropertiesWorks() [Test] public void EmbeddingCollectionWithItemsWorks() { - IEnumerable items = [ - OpenAIEmbeddingsModelFactory.Embedding(index: 10), - OpenAIEmbeddingsModelFactory.Embedding(index: 20) + IEnumerable items = [ + OpenAIEmbeddingsModelFactory.OpenAIEmbedding(index: 10), + OpenAIEmbeddingsModelFactory.OpenAIEmbedding(index: 20) ]; - EmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.EmbeddingCollection(items: items); + OpenAIEmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.OpenAIEmbeddingCollection(items: items); Assert.That(embeddingCollection.SequenceEqual(items), Is.True); Assert.That(embeddingCollection.Model, Is.Null); @@ -67,7 +67,7 @@ public void EmbeddingCollectionWithItemsWorks() public void EmbeddingCollectionWithModelWorks() { string model = "supermodel"; - EmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.EmbeddingCollection(model: model); + OpenAIEmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.OpenAIEmbeddingCollection(model: model); Assert.That(embeddingCollection.Count, Is.EqualTo(0)); Assert.That(embeddingCollection.Model, Is.EqualTo(model)); @@ -78,7 +78,7 @@ public void EmbeddingCollectionWithModelWorks() public void EmbeddingCollectionWithUsageWorks() { EmbeddingTokenUsage usage = OpenAIEmbeddingsModelFactory.EmbeddingTokenUsage(inputTokens: 10); - EmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.EmbeddingCollection(usage: usage); + OpenAIEmbeddingCollection embeddingCollection = OpenAIEmbeddingsModelFactory.OpenAIEmbeddingCollection(usage: usage); Assert.That(embeddingCollection.Count, Is.EqualTo(0)); Assert.That(embeddingCollection.Model, Is.Null); @@ -90,8 +90,8 @@ public void EmbeddingTokenUsageWithNoPropertiesWorks() { EmbeddingTokenUsage embeddingTokenUsage = OpenAIEmbeddingsModelFactory.EmbeddingTokenUsage(); - Assert.That(embeddingTokenUsage.InputTokens, Is.EqualTo(default(int))); - Assert.That(embeddingTokenUsage.TotalTokens, Is.EqualTo(default(int))); + Assert.That(embeddingTokenUsage.InputTokenCount, Is.EqualTo(default(int))); + Assert.That(embeddingTokenUsage.TotalTokenCount, Is.EqualTo(default(int))); } [Test] @@ -100,8 +100,8 @@ public void EmbeddingTokenUsageWithInputTokensWorks() int inputTokens = 10; EmbeddingTokenUsage embeddingTokenUsage = OpenAIEmbeddingsModelFactory.EmbeddingTokenUsage(inputTokens: inputTokens); - Assert.That(embeddingTokenUsage.InputTokens, Is.EqualTo(10)); - Assert.That(embeddingTokenUsage.TotalTokens, Is.EqualTo(default(int))); + Assert.That(embeddingTokenUsage.InputTokenCount, Is.EqualTo(10)); + Assert.That(embeddingTokenUsage.TotalTokenCount, Is.EqualTo(default(int))); } [Test] @@ -110,7 +110,7 @@ public void EmbeddingTokenUsageWithTotalTokensWorks() int totalTokens = 10; EmbeddingTokenUsage embeddingTokenUsage = OpenAIEmbeddingsModelFactory.EmbeddingTokenUsage(totalTokens: totalTokens); - Assert.That(embeddingTokenUsage.InputTokens, Is.EqualTo(default(int))); - Assert.That(embeddingTokenUsage.TotalTokens, Is.EqualTo(totalTokens)); + Assert.That(embeddingTokenUsage.InputTokenCount, Is.EqualTo(default(int))); + Assert.That(embeddingTokenUsage.TotalTokenCount, Is.EqualTo(totalTokens)); } } diff --git a/tests/Files/FilesMockTests.cs b/tests/Files/FilesMockTests.cs index ebb3fc33..f8eb07d2 100644 --- a/tests/Files/FilesMockTests.cs +++ b/tests/Files/FilesMockTests.cs @@ -63,7 +63,7 @@ public async Task GetFileDeserializesId() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfo fileInfo = IsAsync + OpenAIFile fileInfo = IsAsync ? await client.GetFileAsync("file_id") : client.GetFile("file_id"); @@ -80,7 +80,7 @@ public async Task GetFileDeserializesCreatedAt() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfo fileInfo = IsAsync + OpenAIFile fileInfo = IsAsync ? await client.GetFileAsync("file_id") : client.GetFile("file_id"); @@ -98,7 +98,7 @@ public async Task GetFileDeserializesPurpose((string stringValue, OpenAIFilePurp """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfo fileInfo = IsAsync + OpenAIFile fileInfo = IsAsync ? await client.GetFileAsync("file_id") : client.GetFile("file_id"); @@ -118,7 +118,7 @@ public async Task GetFileDeserializesStatus((string stringValue, OpenAIFileStatu """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfo fileInfo = IsAsync + OpenAIFile fileInfo = IsAsync ? await client.GetFileAsync("file_id") : client.GetFile("file_id"); @@ -137,7 +137,7 @@ public async Task GetFileDeserializesStatusDetails() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfo fileInfo = IsAsync + OpenAIFile fileInfo = IsAsync ? await client.GetFileAsync("file_id") : client.GetFile("file_id"); @@ -173,7 +173,7 @@ public async Task UploadFileDeserializesId(FileSourceKind fileSourceKind) "id": "returned_file_id" } """); - OpenAIFileInfo fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); + OpenAIFile fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); Assert.That(fileInfo.Id, Is.EqualTo("returned_file_id")); } @@ -187,7 +187,7 @@ public async Task UploadFileDeserializesCreatedAt(FileSourceKind fileSourceKind) "created_at": 1704096000 } """); - OpenAIFileInfo fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); + OpenAIFile fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); Assert.That(fileInfo.CreatedAt.ToUnixTimeSeconds(), Is.EqualTo(1704096000)); } @@ -202,7 +202,7 @@ public async Task UploadFileDeserializesPurpose( "purpose": "{{purpose.stringValue}}" } """); - OpenAIFileInfo fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); + OpenAIFile fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); Assert.That(fileInfo.Purpose, Is.EqualTo(purpose.expectedValue)); } @@ -218,7 +218,7 @@ public async Task UploadFileDeserializesStatus( "status": "{{status.stringValue}}" } """); - OpenAIFileInfo fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); + OpenAIFile fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); Assert.That(fileInfo.Status, Is.EqualTo(status.expectedValue)); } @@ -234,7 +234,7 @@ public async Task UploadFileDeserializesStatusDetails(FileSourceKind fileSourceK "status_details": "This is definitely an error." } """); - OpenAIFileInfo fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); + OpenAIFile fileInfo = await InvokeUploadFileSyncOrAsync(clientOptions, fileSourceKind); Assert.That(fileInfo.StatusDetails, Is.EqualTo("This is definitely an error.")); } @@ -274,10 +274,10 @@ public async Task GetFilesDeserializesId() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfoCollection fileInfoCollection = IsAsync + OpenAIFileCollection fileInfoCollection = IsAsync ? await client.GetFilesAsync(OpenAIFilePurpose.Assistants) : client.GetFiles(OpenAIFilePurpose.Assistants); - OpenAIFileInfo fileInfo = fileInfoCollection.Single(); + OpenAIFile fileInfo = fileInfoCollection.Single(); Assert.That(fileInfo.Id, Is.EqualTo("returned_file_id")); } @@ -296,10 +296,10 @@ public async Task GetFilesDeserializesCreatedAt() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfoCollection fileInfoCollection = IsAsync + OpenAIFileCollection fileInfoCollection = IsAsync ? await client.GetFilesAsync(OpenAIFilePurpose.Assistants) : client.GetFiles(OpenAIFilePurpose.Assistants); - OpenAIFileInfo fileInfo = fileInfoCollection.Single(); + OpenAIFile fileInfo = fileInfoCollection.Single(); Assert.That(fileInfo.CreatedAt.ToUnixTimeSeconds(), Is.EqualTo(1704096000)); } @@ -319,10 +319,10 @@ public async Task GetFilesDeserializesPurpose((string stringValue, OpenAIFilePur """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfoCollection fileInfoCollection = IsAsync + OpenAIFileCollection fileInfoCollection = IsAsync ? await client.GetFilesAsync(OpenAIFilePurpose.Assistants) : client.GetFiles(OpenAIFilePurpose.Assistants); - OpenAIFileInfo fileInfo = fileInfoCollection.Single(); + OpenAIFile fileInfo = fileInfoCollection.Single(); Assert.That(fileInfo.Purpose, Is.EqualTo(purpose.expectedValue)); } @@ -343,10 +343,10 @@ public async Task GetFilesDeserializesStatus((string stringValue, OpenAIFileStat """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfoCollection fileInfoCollection = IsAsync + OpenAIFileCollection fileInfoCollection = IsAsync ? await client.GetFilesAsync(OpenAIFilePurpose.Assistants) : client.GetFiles(OpenAIFilePurpose.Assistants); - OpenAIFileInfo fileInfo = fileInfoCollection.Single(); + OpenAIFile fileInfo = fileInfoCollection.Single(); Assert.That(fileInfo.Status, Is.EqualTo(status.expectedValue)); } @@ -367,10 +367,10 @@ public async Task GetFilesDeserializesStatusDetails() """); FileClient client = new FileClient(s_fakeCredential, clientOptions); - OpenAIFileInfoCollection fileInfoCollection = IsAsync + OpenAIFileCollection fileInfoCollection = IsAsync ? await client.GetFilesAsync(OpenAIFilePurpose.Assistants) : client.GetFiles(OpenAIFilePurpose.Assistants); - OpenAIFileInfo fileInfo = fileInfoCollection.Single(); + OpenAIFile fileInfo = fileInfoCollection.Single(); Assert.That(fileInfo.StatusDetails, Is.EqualTo("This is definitely an error.")); } @@ -444,7 +444,7 @@ private OpenAIClientOptions GetClientOptionsWithMockResponse(int status, string }; } - private async ValueTask InvokeUploadFileSyncOrAsync(OpenAIClientOptions clientOptions, FileSourceKind fileSourceKind) + private async ValueTask InvokeUploadFileSyncOrAsync(OpenAIClientOptions clientOptions, FileSourceKind fileSourceKind) { FileClient client = new FileClient(s_fakeCredential, clientOptions); string filename = "images_dog_and_cat.png"; diff --git a/tests/Files/FilesTests.cs b/tests/Files/FilesTests.cs index 0ce6f460..cd57f4b0 100644 --- a/tests/Files/FilesTests.cs +++ b/tests/Files/FilesTests.cs @@ -32,10 +32,10 @@ public async Task ListFiles() string visionFilename = "images_dog_and_cat.png"; string visionFilePath = Path.Combine("Assets", visionFilename); - OpenAIFileInfo uploadedFile1 = null; - OpenAIFileInfo uploadedFile2 = null; - OpenAIFileInfo uploadedVisionFile = null; - OpenAIFileInfoCollection fileInfoCollection; + OpenAIFile uploadedFile1 = null; + OpenAIFile uploadedFile2 = null; + OpenAIFile uploadedVisionFile = null; + OpenAIFileCollection fileInfoCollection; try { @@ -65,11 +65,11 @@ public async Task ListFiles() } } - OpenAIFileInfo fileInfo1 = null; - OpenAIFileInfo fileInfo2 = null; - OpenAIFileInfo visionFileInfo = null; + OpenAIFile fileInfo1 = null; + OpenAIFile fileInfo2 = null; + OpenAIFile visionFileInfo = null; - foreach (OpenAIFileInfo item in fileInfoCollection) + foreach (OpenAIFile item in fileInfoCollection) { if (item.Id == uploadedFile1.Id) { @@ -143,7 +143,7 @@ public async Task UploadFile(FileSourceKind fileSourceKind) FileClient client = GetTestClient(); string filename = "images_dog_and_cat.png"; string path = Path.Combine("Assets", filename); - OpenAIFileInfo fileInfo = null; + OpenAIFile fileInfo = null; try { @@ -229,7 +229,7 @@ public async Task DeleteFile(bool useFileInfoOverload) using Stream file = BinaryData.FromString(fileContent).ToStream(); string filename = "test-file-delete-me.txt"; - OpenAIFileInfo uploadedFile = await client.UploadFileAsync(file, filename, FileUploadPurpose.Assistants); + OpenAIFile uploadedFile = await client.UploadFileAsync(file, filename, FileUploadPurpose.Assistants); FileDeletionResult result; if (useFileInfoOverload) @@ -273,8 +273,8 @@ public async Task GetFile() FileClient client = GetTestClient(); using Stream file = BinaryData.FromString("Hello! This is a test text file. Please delete me.").ToStream(); string filename = "test-file-delete-me.txt"; - OpenAIFileInfo uploadedFile = null; - OpenAIFileInfo fileInfo; + OpenAIFile uploadedFile = null; + OpenAIFile fileInfo; try { @@ -329,7 +329,7 @@ public async Task DownloadContent() string filename = "images_dog_and_cat.png"; string path = Path.Combine("Assets", filename); using Stream file = File.OpenRead(path); - OpenAIFileInfo uploadedFile = null; + OpenAIFile uploadedFile = null; BinaryData downloadedContent; try @@ -384,7 +384,7 @@ public async Task NonAsciiFilename() FileClient client = GetTestClient(); string filename = "你好.txt"; BinaryData fileContent = BinaryData.FromString("世界您好!这是个测试。"); - OpenAIFileInfo uploadedFile = IsAsync + OpenAIFile uploadedFile = IsAsync ? await client.UploadFileAsync(fileContent, filename, FileUploadPurpose.Assistants) : client.UploadFile(fileContent, filename, FileUploadPurpose.Assistants); Assert.That(uploadedFile?.Filename, Is.EqualTo(filename)); diff --git a/tests/Files/OpenAIFilesModelFactoryTests.cs b/tests/Files/OpenAIFilesModelFactoryTests.cs index 4fd5940e..c6f94a93 100644 --- a/tests/Files/OpenAIFilesModelFactoryTests.cs +++ b/tests/Files/OpenAIFilesModelFactoryTests.cs @@ -44,7 +44,7 @@ public void FileDeletionResultWithDeletedWorks() [Test] public void OpenAIFileInfoWithNoPropertiesWorks() { - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(); + OpenAIFile openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(); Assert.That(openAIFileInfo.Id, Is.Null); Assert.That(openAIFileInfo.SizeInBytes, Is.Null); @@ -61,7 +61,7 @@ public void OpenAIFileInfoWithNoPropertiesWorks() public void OpenAIFileInfoWithIdWorks() { string id = "fileId"; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(id: id); + OpenAIFile openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(id: id); Assert.That(openAIFileInfo.Id, Is.EqualTo(id)); Assert.That(openAIFileInfo.SizeInBytes, Is.Null); @@ -78,15 +78,15 @@ public void OpenAIFileInfoWithIdWorks() public void OpenAIFileInfoWithSizeInBytesWorks() { int sizeInBytes = 1025; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(sizeInBytes: sizeInBytes); - - Assert.That(openAIFileInfo.Id, Is.Null); - Assert.That(openAIFileInfo.SizeInBytes, Is.EqualTo(sizeInBytes)); - Assert.That(openAIFileInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIFileInfo.Filename, Is.Null); - Assert.That(openAIFileInfo.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); - Assert.That(openAIFileInfo.Status, Is.EqualTo(default(OpenAIFileStatus))); - Assert.That(openAIFileInfo.StatusDetails, Is.Null); + OpenAIFile openAIFile = OpenAIFilesModelFactory.OpenAIFileInfo(sizeInBytes: sizeInBytes); + + Assert.That(openAIFile.Id, Is.Null); + Assert.That(openAIFile.SizeInBytes, Is.EqualTo(sizeInBytes)); + Assert.That(openAIFile.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIFile.Filename, Is.Null); + Assert.That(openAIFile.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); + Assert.That(openAIFile.Status, Is.EqualTo(default(OpenAIFileStatus))); + Assert.That(openAIFile.StatusDetails, Is.Null); } #pragma warning restore CS0618 @@ -95,7 +95,7 @@ public void OpenAIFileInfoWithSizeInBytesWorks() public void OpenAIFileInfoWithCreatedAtWorks() { DateTimeOffset createdAt = DateTimeOffset.UtcNow; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(createdAt: createdAt); + OpenAIFile openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(createdAt: createdAt); Assert.That(openAIFileInfo.Id, Is.Null); Assert.That(openAIFileInfo.SizeInBytes, Is.Null); @@ -112,15 +112,15 @@ public void OpenAIFileInfoWithCreatedAtWorks() public void OpenAIFileInfoWithFilenameWorks() { string filename = "file.png"; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(filename: filename); - - Assert.That(openAIFileInfo.Id, Is.Null); - Assert.That(openAIFileInfo.SizeInBytes, Is.Null); - Assert.That(openAIFileInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIFileInfo.Filename, Is.EqualTo(filename)); - Assert.That(openAIFileInfo.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); - Assert.That(openAIFileInfo.Status, Is.EqualTo(default(OpenAIFileStatus))); - Assert.That(openAIFileInfo.StatusDetails, Is.Null); + OpenAIFile openAIFile = OpenAIFilesModelFactory.OpenAIFileInfo(filename: filename); + + Assert.That(openAIFile.Id, Is.Null); + Assert.That(openAIFile.SizeInBytes, Is.Null); + Assert.That(openAIFile.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIFile.Filename, Is.EqualTo(filename)); + Assert.That(openAIFile.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); + Assert.That(openAIFile.Status, Is.EqualTo(default(OpenAIFileStatus))); + Assert.That(openAIFile.StatusDetails, Is.Null); } #pragma warning restore CS0618 @@ -129,15 +129,15 @@ public void OpenAIFileInfoWithFilenameWorks() public void OpenAIFileInfoWithPurposeWorks() { OpenAIFilePurpose purpose = OpenAIFilePurpose.Vision; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(purpose: purpose); - - Assert.That(openAIFileInfo.Id, Is.Null); - Assert.That(openAIFileInfo.SizeInBytes, Is.Null); - Assert.That(openAIFileInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIFileInfo.Filename, Is.Null); - Assert.That(openAIFileInfo.Purpose, Is.EqualTo(purpose)); - Assert.That(openAIFileInfo.Status, Is.EqualTo(default(OpenAIFileStatus))); - Assert.That(openAIFileInfo.StatusDetails, Is.Null); + OpenAIFile openAIFile = OpenAIFilesModelFactory.OpenAIFileInfo(purpose: purpose); + + Assert.That(openAIFile.Id, Is.Null); + Assert.That(openAIFile.SizeInBytes, Is.Null); + Assert.That(openAIFile.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIFile.Filename, Is.Null); + Assert.That(openAIFile.Purpose, Is.EqualTo(purpose)); + Assert.That(openAIFile.Status, Is.EqualTo(default(OpenAIFileStatus))); + Assert.That(openAIFile.StatusDetails, Is.Null); } #pragma warning restore CS0618 @@ -146,15 +146,15 @@ public void OpenAIFileInfoWithPurposeWorks() public void OpenAIFileInfoWithStatusWorks() { OpenAIFileStatus status = OpenAIFileStatus.Uploaded; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(status: status); - - Assert.That(openAIFileInfo.Id, Is.Null); - Assert.That(openAIFileInfo.SizeInBytes, Is.Null); - Assert.That(openAIFileInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIFileInfo.Filename, Is.Null); - Assert.That(openAIFileInfo.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); - Assert.That(openAIFileInfo.Status, Is.EqualTo(status)); - Assert.That(openAIFileInfo.StatusDetails, Is.Null); + OpenAIFile openAIFile = OpenAIFilesModelFactory.OpenAIFileInfo(status: status); + + Assert.That(openAIFile.Id, Is.Null); + Assert.That(openAIFile.SizeInBytes, Is.Null); + Assert.That(openAIFile.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIFile.Filename, Is.Null); + Assert.That(openAIFile.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); + Assert.That(openAIFile.Status, Is.EqualTo(status)); + Assert.That(openAIFile.StatusDetails, Is.Null); } #pragma warning restore CS0618 @@ -163,22 +163,22 @@ public void OpenAIFileInfoWithStatusWorks() public void OpenAIFileInfoWithStatusDetailsWorks() { string statusDetails = "There's something off about this file."; - OpenAIFileInfo openAIFileInfo = OpenAIFilesModelFactory.OpenAIFileInfo(statusDetails: statusDetails); - - Assert.That(openAIFileInfo.Id, Is.Null); - Assert.That(openAIFileInfo.SizeInBytes, Is.Null); - Assert.That(openAIFileInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIFileInfo.Filename, Is.Null); - Assert.That(openAIFileInfo.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); - Assert.That(openAIFileInfo.Status, Is.EqualTo(default(OpenAIFileStatus))); - Assert.That(openAIFileInfo.StatusDetails, Is.EqualTo(statusDetails)); + OpenAIFile openAIFile = OpenAIFilesModelFactory.OpenAIFileInfo(statusDetails: statusDetails); + + Assert.That(openAIFile.Id, Is.Null); + Assert.That(openAIFile.SizeInBytes, Is.Null); + Assert.That(openAIFile.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIFile.Filename, Is.Null); + Assert.That(openAIFile.Purpose, Is.EqualTo(default(OpenAIFilePurpose))); + Assert.That(openAIFile.Status, Is.EqualTo(default(OpenAIFileStatus))); + Assert.That(openAIFile.StatusDetails, Is.EqualTo(statusDetails)); } #pragma warning restore CS0618 [Test] public void OpenAIFileInfoCollectionWithNoPropertiesWorks() { - OpenAIFileInfoCollection openAIFileInfoCollection = OpenAIFilesModelFactory.OpenAIFileInfoCollection(); + OpenAIFileCollection openAIFileInfoCollection = OpenAIFilesModelFactory.OpenAIFileCollection(); Assert.That(openAIFileInfoCollection.Count, Is.EqualTo(0)); } @@ -186,12 +186,12 @@ public void OpenAIFileInfoCollectionWithNoPropertiesWorks() [Test] public void OpenAIFileInfoCollectionWithItemsWorks() { - IEnumerable items = [ + IEnumerable items = [ OpenAIFilesModelFactory.OpenAIFileInfo(id: "firstFile"), OpenAIFilesModelFactory.OpenAIFileInfo(id: "secondFile") ]; - OpenAIFileInfoCollection openAIFileInfoCollection = OpenAIFilesModelFactory.OpenAIFileInfoCollection(items: items); + OpenAIFileCollection openAIFileCollection = OpenAIFilesModelFactory.OpenAIFileCollection(items: items); - Assert.That(openAIFileInfoCollection.SequenceEqual(items), Is.True); + Assert.That(openAIFileCollection.SequenceEqual(items), Is.True); } } diff --git a/tests/Models/ModelsMockTests.cs b/tests/Models/ModelsMockTests.cs index 73b3d86e..2777d07e 100644 --- a/tests/Models/ModelsMockTests.cs +++ b/tests/Models/ModelsMockTests.cs @@ -31,7 +31,7 @@ public async Task GetModelDeserializesCreatedAt() """); ModelClient client = new ModelClient(s_fakeCredential, clientOptions); - OpenAIModelInfo modelInfo = IsAsync + OpenAIModel modelInfo = IsAsync ? await client.GetModelAsync("model_name") : client.GetModel("model_name"); @@ -52,10 +52,10 @@ public async Task GetModelsDeserializesCreatedAt() """); ModelClient client = new ModelClient(s_fakeCredential, clientOptions); - OpenAIModelInfoCollection modelInfoCollection = IsAsync + OpenAIModelCollection modelInfoCollection = IsAsync ? await client.GetModelsAsync() : client.GetModels(); - OpenAIModelInfo modelInfo = modelInfoCollection.Single(); + OpenAIModel modelInfo = modelInfoCollection.Single(); Assert.That(modelInfo.CreatedAt.ToUnixTimeSeconds(), Is.EqualTo(1704096000)); } diff --git a/tests/Models/ModelsTests.cs b/tests/Models/ModelsTests.cs index 6966ca6e..7d0794f5 100644 --- a/tests/Models/ModelsTests.cs +++ b/tests/Models/ModelsTests.cs @@ -24,12 +24,12 @@ public async Task ListModels() { ModelClient client = GetTestClient(TestScenario.Models); - OpenAIModelInfoCollection allModels = IsAsync + OpenAIModelCollection allModels = IsAsync ? await client.GetModelsAsync() : client.GetModels(); - OpenAIModelInfo whisper = allModels.First(m => m.Id.Contains("whisper", StringComparison.InvariantCultureIgnoreCase)); - OpenAIModelInfo turbo = allModels.First(m => m.Id.Contains("turbo", StringComparison.InvariantCultureIgnoreCase)); + OpenAIModel whisper = allModels.First(m => m.Id.Contains("whisper", StringComparison.InvariantCultureIgnoreCase)); + OpenAIModel turbo = allModels.First(m => m.Id.Contains("turbo", StringComparison.InvariantCultureIgnoreCase)); long unixTime2020 = (new DateTimeOffset(2020, 01, 01, 0, 0, 0, TimeSpan.Zero)).ToUnixTimeSeconds(); Assert.That(whisper.Id, Is.Not.EqualTo(turbo.Id)); @@ -47,7 +47,7 @@ public async Task GetModelInfo() ModelClient client = GetTestClient(TestScenario.Models); string modelId = "gpt-4o-mini"; - OpenAIModelInfo model = IsAsync + OpenAIModel model = IsAsync ? await client.GetModelAsync(modelId) : client.GetModel(modelId); diff --git a/tests/Models/OpenAIModelsModelFactoryTests.cs b/tests/Models/OpenAIModelsModelFactoryTests.cs index fc9ecfe2..2b6a33ff 100644 --- a/tests/Models/OpenAIModelsModelFactoryTests.cs +++ b/tests/Models/OpenAIModelsModelFactoryTests.cs @@ -41,65 +41,65 @@ public void ModelDeletionResultWithDeletedWorks() } [Test] - public void OpenAIModelInfoWithNoPropertiesWorks() + public void OpenAIModelWithNoPropertiesWorks() { - OpenAIModelInfo openAIModelInfo = OpenAIModelsModelFactory.OpenAIModelInfo(); + OpenAIModel openAIModel = OpenAIModelsModelFactory.OpenAIModel(); - Assert.That(openAIModelInfo.Id, Is.Null); - Assert.That(openAIModelInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIModelInfo.OwnedBy, Is.Null); + Assert.That(openAIModel.Id, Is.Null); + Assert.That(openAIModel.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIModel.OwnedBy, Is.Null); } [Test] - public void OpenAIModelInfoWithIdWorks() + public void OpenAIModelWithIdWorks() { string id = "modelId"; - OpenAIModelInfo openAIModelInfo = OpenAIModelsModelFactory.OpenAIModelInfo(id: id); + OpenAIModel openAIModel = OpenAIModelsModelFactory.OpenAIModel(id: id); - Assert.That(openAIModelInfo.Id, Is.EqualTo(id)); - Assert.That(openAIModelInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIModelInfo.OwnedBy, Is.Null); + Assert.That(openAIModel.Id, Is.EqualTo(id)); + Assert.That(openAIModel.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIModel.OwnedBy, Is.Null); } [Test] - public void OpenAIModelInfoWithCreatedAtWorks() + public void OpenAIModelWithCreatedAtWorks() { DateTimeOffset createdAt = DateTimeOffset.UtcNow; - OpenAIModelInfo openAIModelInfo = OpenAIModelsModelFactory.OpenAIModelInfo(createdAt: createdAt); + OpenAIModel openAIModel = OpenAIModelsModelFactory.OpenAIModel(createdAt: createdAt); - Assert.That(openAIModelInfo.Id, Is.Null); - Assert.That(openAIModelInfo.CreatedAt, Is.EqualTo(createdAt)); - Assert.That(openAIModelInfo.OwnedBy, Is.Null); + Assert.That(openAIModel.Id, Is.Null); + Assert.That(openAIModel.CreatedAt, Is.EqualTo(createdAt)); + Assert.That(openAIModel.OwnedBy, Is.Null); } [Test] - public void OpenAIModelInfoWithOwnedByWorks() + public void OpenAIModelWithOwnedByWorks() { string ownedBy = "The people"; - OpenAIModelInfo openAIModelInfo = OpenAIModelsModelFactory.OpenAIModelInfo(ownedBy: ownedBy); + OpenAIModel openAIModel = OpenAIModelsModelFactory.OpenAIModel(ownedBy: ownedBy); - Assert.That(openAIModelInfo.Id, Is.Null); - Assert.That(openAIModelInfo.CreatedAt, Is.EqualTo(default(DateTimeOffset))); - Assert.That(openAIModelInfo.OwnedBy, Is.EqualTo(ownedBy)); + Assert.That(openAIModel.Id, Is.Null); + Assert.That(openAIModel.CreatedAt, Is.EqualTo(default(DateTimeOffset))); + Assert.That(openAIModel.OwnedBy, Is.EqualTo(ownedBy)); } [Test] - public void OpenAIModelInfoCollectionWithNoPropertiesWorks() + public void OpenAIModelCollectionWithNoPropertiesWorks() { - OpenAIModelInfoCollection openAIModelInfoCollection = OpenAIModelsModelFactory.OpenAIModelInfoCollection(); + OpenAIModelCollection openAIModelCollection = OpenAIModelsModelFactory.OpenAIModelCollection(); - Assert.That(openAIModelInfoCollection.Count, Is.EqualTo(0)); + Assert.That(openAIModelCollection.Count, Is.EqualTo(0)); } [Test] - public void OpenAIModelInfoCollectionWithItemsWorks() + public void OpenAIModelCollectionWithItemsWorks() { - IEnumerable items = [ - OpenAIModelsModelFactory.OpenAIModelInfo(id: "firstModel"), - OpenAIModelsModelFactory.OpenAIModelInfo(id: "secondModel") + IEnumerable items = [ + OpenAIModelsModelFactory.OpenAIModel(id: "firstModel"), + OpenAIModelsModelFactory.OpenAIModel(id: "secondModel") ]; - OpenAIModelInfoCollection openAIModelInfoCollection = OpenAIModelsModelFactory.OpenAIModelInfoCollection(items: items); + OpenAIModelCollection openAIModelCollection = OpenAIModelsModelFactory.OpenAIModelCollection(items: items); - Assert.That(openAIModelInfoCollection.SequenceEqual(items), Is.True); + Assert.That(openAIModelCollection.SequenceEqual(items), Is.True); } } diff --git a/tests/Moderations/ModerationSmokeTests.cs b/tests/Moderations/ModerationSmokeTests.cs new file mode 100644 index 00000000..323613f0 --- /dev/null +++ b/tests/Moderations/ModerationSmokeTests.cs @@ -0,0 +1,269 @@ +using NUnit.Framework; +using OpenAI.Moderations; +using OpenAI.Tests.Utility; +using System.ClientModel; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace OpenAI.Tests.Moderations; + +[TestFixture(true)] +[TestFixture(false)] +[Parallelizable(ParallelScope.All)] +[Category("Moderations")] +[Category("Smoke")] +public partial class ModerationSmokeTests : SyncAsyncTestBase +{ + public ModerationSmokeTests(bool isAsync) : base(isAsync) + { + } + + [Test] + public async Task ClassifySingleInputSmokeTest() + { + BinaryData mockRequest = BinaryData.FromString($$""" + { + "input": "I am killing all my houseplants!" + } + """); + BinaryData mockResponse = BinaryData.FromString($$""" + { + "results": [ + { + "flagged": true, + "categories": { + "violence": true + }, + "category_scores": { + "violence": 0.5 + } + } + ] + } + """); + MockPipelineTransport mockTransport = new(mockRequest, mockResponse); + + OpenAIClientOptions options = new() + { + Transport = mockTransport + }; + + ModerationClient client = new ModerationClient("model", new ApiKeyCredential("sk-not-a-real-key"), options); + ModerationResult moderation = IsAsync + ? await client.ClassifyTextAsync("Mock me!") + : client.ClassifyText("Mock me!"); + + Assert.That(moderation, Is.Not.Null); + Assert.That(moderation.Flagged, Is.True); + Assert.That(moderation.Violence.Flagged, Is.True); + Assert.That(moderation.Violence.Score, Is.EqualTo(0.5f)); + } + + [Test] + public async Task ClassifyMultipleInputsSmokeTest() + { + BinaryData mockRequest = BinaryData.FromString($$""" + { + "input": [ + "I forgot to water my houseplants!", + "I am killing all my houseplants!" + ] + } + """); + BinaryData mockResponse = BinaryData.FromString($$""" + { + "results": [ + { + "flagged": false, + "categories": { + "violence": false + }, + "category_scores": { + "violence": 0.0 + } + }, + { + "flagged": true, + "categories": { + "violence": true + }, + "category_scores": { + "violence": 0.5 + } + } + ] + } + """); + + MockPipelineTransport mockTransport = new(mockRequest, mockResponse); + + OpenAIClientOptions options = new() + { + Transport = mockTransport + }; + + ModerationClient client = new ModerationClient("model", new ApiKeyCredential("sk-not-a-real-key"), options); + ModerationResultCollection moderations = IsAsync + ? await client.ClassifyTextAsync(new List { "Mock me 1!", "Mock me 2!" }) + : client.ClassifyText(new List { "Mock me 1!", "Mock me 2!" }); + + Assert.That(moderations, Is.Not.Null); + Assert.That(moderations.Count, Is.EqualTo(2)); + + Assert.That(moderations[0], Is.Not.Null); + Assert.That(moderations[0].Flagged, Is.False); + + Assert.That(moderations[1], Is.Not.Null); + Assert.That(moderations[1].Flagged, Is.True); + Assert.That(moderations[1].Violence.Flagged, Is.True); + Assert.That(moderations[1].Violence.Score, Is.EqualTo(0.5f)); + } + + [Test] + public void SerializeModerationResult() + { + BinaryData data = BinaryData.FromString($$""" + { + "flagged": true, + "categories": { + "violence": true + }, + "category_scores": { + "violence": 0.5 + } + } + """); + + // Deserialize the raw JSON and then serialize it back to confirm nothing was lost. + ModerationResult moderationResult = ModelReaderWriter.Read(data); + Assert.That(moderationResult.Flagged, Is.EqualTo(true)); + Assert.That(moderationResult.Violence.Flagged, Is.EqualTo(true)); + Assert.That(moderationResult.Violence.Score, Is.EqualTo(0.5f)); + + BinaryData serializedPart = ModelReaderWriter.Write(moderationResult); + using JsonDocument partAsJson = JsonDocument.Parse(serializedPart); + Assert.That(partAsJson.RootElement, Is.Not.Null); + Assert.That(partAsJson.RootElement.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(partAsJson.RootElement.TryGetProperty("flagged", out JsonElement flagged), Is.True); + Assert.That(flagged, Is.Not.Null); + Assert.That(flagged.ValueKind, Is.EqualTo(JsonValueKind.True)); + + // Access and assert the "categories" object and its "violence" value + Assert.That(partAsJson.RootElement.TryGetProperty("categories", out JsonElement categories), Is.True); + Assert.That(categories, Is.Not.Null); + Assert.That(categories.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categories.TryGetProperty("violence", out JsonElement violenceCategory), Is.True); + Assert.That(violenceCategory, Is.Not.Null); + Assert.That(violenceCategory.ValueKind, Is.EqualTo(JsonValueKind.True)); + + // Access and assert the "category_scores" object and its "violence" value + Assert.That(partAsJson.RootElement.TryGetProperty("category_scores", out JsonElement categoryScores), Is.True); + Assert.That(categoryScores, Is.Not.Null); + Assert.That(categoryScores.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categoryScores.TryGetProperty("violence", out JsonElement violenceScore), Is.True); + Assert.That(violenceScore, Is.Not.Null); + Assert.That(violenceScore.ValueKind, Is.EqualTo(JsonValueKind.Number)); + Assert.That(violenceScore.GetSingle(), Is.EqualTo(0.5f)); + } + + [Test] + public void SerializeModerationResultCollection() + { + BinaryData data = BinaryData.FromString($$""" + { + "results": [ + { + "flagged": false, + "categories": { + "violence": false + }, + "category_scores": { + "violence": 0.0 + } + }, + { + "flagged": true, + "categories": { + "violence": true + }, + "category_scores": { + "violence": 0.5 + } + } + ] + } + """); + + // Deserialize the raw JSON and then serialize it back to confirm nothing was lost. + ModerationResultCollection moderations = ModelReaderWriter.Read(data); + Assert.That(moderations[0], Is.Not.Null); + Assert.That(moderations[0].Flagged, Is.False); + + Assert.That(moderations[1], Is.Not.Null); + Assert.That(moderations[1].Flagged, Is.True); + Assert.That(moderations[1].Violence.Flagged, Is.True); + Assert.That(moderations[1].Violence.Score, Is.EqualTo(0.5f)); + + BinaryData serializedPart = ModelReaderWriter.Write(moderations); + using JsonDocument partAsJson = JsonDocument.Parse(serializedPart); + Assert.That(partAsJson.RootElement, Is.Not.Null); + Assert.That(partAsJson.RootElement.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + // Access the "results" array + Assert.That(partAsJson.RootElement.TryGetProperty("results", out JsonElement results), Is.True); + Assert.That(results, Is.Not.Null); + Assert.That(results.ValueKind, Is.EqualTo(JsonValueKind.Array)); + + // Access the first object in the results array and verify its properties + JsonElement firstResult = results[0]; + Assert.That(firstResult.TryGetProperty("flagged", out JsonElement flagged1), Is.True); + Assert.That(flagged1, Is.Not.Null); + Assert.That(flagged1.ValueKind, Is.EqualTo(JsonValueKind.False)); + + Assert.That(firstResult.TryGetProperty("categories", out JsonElement categories1), Is.True); + Assert.That(categories1, Is.Not.Null); + Assert.That(categories1.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categories1.TryGetProperty("violence", out JsonElement violenceCategory1), Is.True); + Assert.That(violenceCategory1, Is.Not.Null); + Assert.That(violenceCategory1.ValueKind, Is.EqualTo(JsonValueKind.False)); // Assert violence is false + + Assert.That(firstResult.TryGetProperty("category_scores", out JsonElement categoryScores1), Is.True); + Assert.That(categoryScores1, Is.Not.Null); + Assert.That(categoryScores1.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categoryScores1.TryGetProperty("violence", out JsonElement violenceScore1), Is.True); + Assert.That(violenceScore1, Is.Not.Null); + Assert.That(violenceScore1.ValueKind, Is.EqualTo(JsonValueKind.Number)); + Assert.That(violenceScore1.GetDouble(), Is.EqualTo(0.0)); // Assert violence score is 0.0 + + // Access the second object in the results array and verify its properties + JsonElement secondResult = results[1]; + Assert.That(secondResult.TryGetProperty("flagged", out JsonElement flagged2), Is.True); + Assert.That(flagged2, Is.Not.Null); + Assert.That(flagged2.ValueKind, Is.EqualTo(JsonValueKind.True)); + + Assert.That(secondResult.TryGetProperty("categories", out JsonElement categories2), Is.True); + Assert.That(categories2, Is.Not.Null); + Assert.That(categories2.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categories2.TryGetProperty("violence", out JsonElement violenceCategory2), Is.True); + Assert.That(violenceCategory2, Is.Not.Null); + Assert.That(violenceCategory2.ValueKind, Is.EqualTo(JsonValueKind.True)); // Assert violence is true + + Assert.That(secondResult.TryGetProperty("category_scores", out JsonElement categoryScores2), Is.True); + Assert.That(categoryScores2, Is.Not.Null); + Assert.That(categoryScores2.ValueKind, Is.EqualTo(JsonValueKind.Object)); + + Assert.That(categoryScores2.TryGetProperty("violence", out JsonElement violenceScore2), Is.True); + Assert.That(violenceScore2, Is.Not.Null); + Assert.That(violenceScore2.ValueKind, Is.EqualTo(JsonValueKind.Number)); + Assert.That(violenceScore2.GetDouble(), Is.EqualTo(0.5)); // Assert violence score is 0.5 + } +} diff --git a/tests/Moderations/ModerationsMockTests.cs b/tests/Moderations/ModerationsMockTests.cs index ad3f7219..07b847da 100644 --- a/tests/Moderations/ModerationsMockTests.cs +++ b/tests/Moderations/ModerationsMockTests.cs @@ -347,7 +347,7 @@ public async Task ClassifyTextInputsDeserializesHateCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -374,7 +374,7 @@ public async Task ClassifyTextInputsDeserializesHateThreateningCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -401,7 +401,7 @@ public async Task ClassifyTextInputsDeserializesHarassmentCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -428,7 +428,7 @@ public async Task ClassifyTextInputsDeserializesHarassmentThreateningCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -455,7 +455,7 @@ public async Task ClassifyTextInputsDeserializesSelfHarmCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -482,7 +482,7 @@ public async Task ClassifyTextInputsDeserializesSelfHarmIntentCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -509,7 +509,7 @@ public async Task ClassifyTextInputsDeserializesSelfHarmInstructionsCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -536,7 +536,7 @@ public async Task ClassifyTextInputsDeserializesSexualCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -563,7 +563,7 @@ public async Task ClassifyTextInputsDeserializesSexualMinorsCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -590,7 +590,7 @@ public async Task ClassifyTextInputsDeserializesViolenceCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -617,7 +617,7 @@ public async Task ClassifyTextInputsDeserializesViolenceGraphicCategory() """); ModerationClient client = new ModerationClient("model", s_fakeCredential, clientOptions); - ModerationCollection resultCollection = IsAsync + ModerationResultCollection resultCollection = IsAsync ? await client.ClassifyTextAsync(["input"]) : client.ClassifyText(["input"]); ModerationResult moderation = resultCollection.Single(); @@ -658,29 +658,29 @@ private void AssertModerationCategories( (bool flagged, float score) violence = default, (bool flagged, float score) violenceGraphic = default) { - Assert.That(moderation.Categories.Hate, Is.EqualTo(hate.flagged)); - Assert.That(moderation.Categories.HateThreatening, Is.EqualTo(hateThreatening.flagged)); - Assert.That(moderation.Categories.Harassment, Is.EqualTo(harassment.flagged)); - Assert.That(moderation.Categories.HarassmentThreatening, Is.EqualTo(harassmentThreatening.flagged)); - Assert.That(moderation.Categories.SelfHarm, Is.EqualTo(selfHarm.flagged)); - Assert.That(moderation.Categories.SelfHarmIntent, Is.EqualTo(selfHarmIntent.flagged)); - Assert.That(moderation.Categories.SelfHarmInstructions, Is.EqualTo(selfHarmInstructions.flagged)); - Assert.That(moderation.Categories.Sexual, Is.EqualTo(sexual.flagged)); - Assert.That(moderation.Categories.SexualMinors, Is.EqualTo(sexualMinors.flagged)); - Assert.That(moderation.Categories.Violence, Is.EqualTo(violence.flagged)); - Assert.That(moderation.Categories.ViolenceGraphic, Is.EqualTo(violenceGraphic.flagged)); - - Assert.That(moderation.CategoryScores.Hate, Is.EqualTo(hate.score)); - Assert.That(moderation.CategoryScores.HateThreatening, Is.EqualTo(hateThreatening.score)); - Assert.That(moderation.CategoryScores.Harassment, Is.EqualTo(harassment.score)); - Assert.That(moderation.CategoryScores.HarassmentThreatening, Is.EqualTo(harassmentThreatening.score)); - Assert.That(moderation.CategoryScores.SelfHarm, Is.EqualTo(selfHarm.score)); - Assert.That(moderation.CategoryScores.SelfHarmIntent, Is.EqualTo(selfHarmIntent.score)); - Assert.That(moderation.CategoryScores.SelfHarmInstructions, Is.EqualTo(selfHarmInstructions.score)); - Assert.That(moderation.CategoryScores.Sexual, Is.EqualTo(sexual.score)); - Assert.That(moderation.CategoryScores.SexualMinors, Is.EqualTo(sexualMinors.score)); - Assert.That(moderation.CategoryScores.Violence, Is.EqualTo(violence.score)); - Assert.That(moderation.CategoryScores.ViolenceGraphic, Is.EqualTo(violenceGraphic.score)); + Assert.That(moderation.Hate.Flagged, Is.EqualTo(hate.flagged)); + Assert.That(moderation.HateThreatening.Flagged, Is.EqualTo(hateThreatening.flagged)); + Assert.That(moderation.Harassment.Flagged, Is.EqualTo(harassment.flagged)); + Assert.That(moderation.HarassmentThreatening.Flagged, Is.EqualTo(harassmentThreatening.flagged)); + Assert.That(moderation.SelfHarm.Flagged, Is.EqualTo(selfHarm.flagged)); + Assert.That(moderation.SelfHarmIntent.Flagged, Is.EqualTo(selfHarmIntent.flagged)); + Assert.That(moderation.SelfHarmInstructions.Flagged, Is.EqualTo(selfHarmInstructions.flagged)); + Assert.That(moderation.Sexual.Flagged, Is.EqualTo(sexual.flagged)); + Assert.That(moderation.SexualMinors.Flagged, Is.EqualTo(sexualMinors.flagged)); + Assert.That(moderation.Violence.Flagged, Is.EqualTo(violence.flagged)); + Assert.That(moderation.ViolenceGraphic.Flagged, Is.EqualTo(violenceGraphic.flagged)); + + Assert.That(moderation.Hate.Score, Is.EqualTo(hate.score)); + Assert.That(moderation.HateThreatening.Score, Is.EqualTo(hateThreatening.score)); + Assert.That(moderation.Harassment.Score, Is.EqualTo(harassment.score)); + Assert.That(moderation.HarassmentThreatening.Score, Is.EqualTo(harassmentThreatening.score)); + Assert.That(moderation.SelfHarm.Score, Is.EqualTo(selfHarm.score)); + Assert.That(moderation.SelfHarmIntent.Score, Is.EqualTo(selfHarmIntent.score)); + Assert.That(moderation.SelfHarmInstructions.Score, Is.EqualTo(selfHarmInstructions.score)); + Assert.That(moderation.Sexual.Score, Is.EqualTo(sexual.score)); + Assert.That(moderation.SexualMinors.Score, Is.EqualTo(sexualMinors.score)); + Assert.That(moderation.Violence.Score, Is.EqualTo(violence.score)); + Assert.That(moderation.ViolenceGraphic.Score, Is.EqualTo(violenceGraphic.score)); } private OpenAIClientOptions GetClientOptionsWithMockResponse(int status, string content) diff --git a/tests/Moderations/ModerationsTests.cs b/tests/Moderations/ModerationsTests.cs index 09d36bb8..2ea2e960 100644 --- a/tests/Moderations/ModerationsTests.cs +++ b/tests/Moderations/ModerationsTests.cs @@ -29,8 +29,8 @@ public async Task ClassifySingleInput() : client.ClassifyText(input); Assert.That(moderation, Is.Not.Null); Assert.That(moderation.Flagged, Is.True); - Assert.That(moderation.Categories.Violence, Is.True); - Assert.That(moderation.CategoryScores.Violence, Is.GreaterThan(0.5)); + Assert.That(moderation.Violence.Flagged, Is.True); + Assert.That(moderation.Violence.Score, Is.GreaterThan(0.5)); } [Test] @@ -44,7 +44,7 @@ public async Task ClassifyMultipleInputs() "I am killing all my houseplants!" ]; - ModerationCollection moderations = IsAsync + ModerationResultCollection moderations = IsAsync ? await client.ClassifyTextAsync(inputs) : client.ClassifyText(inputs); Assert.That(moderations, Is.Not.Null); @@ -57,13 +57,7 @@ public async Task ClassifyMultipleInputs() Assert.That(moderations[1], Is.Not.Null); Assert.That(moderations[1].Flagged, Is.True); - Assert.That(moderations[1].Categories.Violence, Is.True); - Assert.That(moderations[1].CategoryScores.Violence, Is.GreaterThan(0.5)); - } - - [Test] - public void SerializeModerationCollection() - { - // TODO: Add this test. + Assert.That(moderations[1].Violence.Flagged, Is.True); + Assert.That(moderations[1].Violence.Score, Is.GreaterThan(0.5)); } } diff --git a/tests/Moderations/OpenAIModerationsModelFactoryTests.cs b/tests/Moderations/OpenAIModerationsModelFactoryTests.cs index 082859fa..9abed970 100644 --- a/tests/Moderations/OpenAIModerationsModelFactoryTests.cs +++ b/tests/Moderations/OpenAIModerationsModelFactoryTests.cs @@ -12,452 +12,308 @@ namespace OpenAI.Tests.Moderations; public partial class OpenAIModerationsModelFactoryTests { [Test] - public void ModerationCategoriesWithNoPropertiesWorks() + public void ModerationCategoryWithNoPropertiesWorks() { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + ModerationCategory moderationCategory = OpenAIModerationsModelFactory.ModerationCategory(); - [Test] - public void ModerationCategoriesWithHateWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(hate: true); - - Assert.That(moderationCategories.Hate, Is.True); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); + Assert.That(moderationCategory.Flagged, Is.False); + Assert.That(moderationCategory.Score, Is.EqualTo(0f)); } [Test] - public void ModerationCategoriesWithHateThreateningWorks() + public void ModerationCategoryWithFlagWorks() { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(hateThreatening: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.True); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + ModerationCategory moderationCategory = OpenAIModerationsModelFactory.ModerationCategory(flagged: true); - [Test] - public void ModerationCategoriesWithHarassmentWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(harassment: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.True); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); + Assert.That(moderationCategory.Flagged, Is.True); + Assert.That(moderationCategory.Score, Is.EqualTo(0f)); } [Test] - public void ModerationCategoriesWithHarassmentThreateningWorks() + public void ModerationCategoryWithScoreWorks() { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(harassmentThreatening: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.True); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + ModerationCategory moderationCategory = OpenAIModerationsModelFactory.ModerationCategory(score: 0.85f); - [Test] - public void ModerationCategoriesWithSelfHarmWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(selfHarm: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.True); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); + Assert.That(moderationCategory.Flagged, Is.False); + Assert.That(moderationCategory.Score, Is.EqualTo(0.85f)); } [Test] - public void ModerationCategoriesWithSelfHarmIntentWorks() + public void ModerationResultWithNoPropertiesWorks() { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(selfHarmIntent: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.True); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(); - [Test] - public void ModerationCategoriesWithSelfHarmInstructionWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(selfHarmInstructions: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.True); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + Assert.That(moderationResult.Flagged, Is.False); - [Test] - public void ModerationCategoriesWithSexualWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(sexual: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.True); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoriesWithSexualMinorsWorks() + public void ModerationResultWithHateWorks() { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(sexualMinors: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.True); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + float hateScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, hateScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(hate: category); - [Test] - public void ModerationCategoriesWithViolenceWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(violence: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.True); - Assert.That(moderationCategories.ViolenceGraphic, Is.False); - } + Assert.That(moderationResult.Hate.Flagged, Is.True); + Assert.That(moderationResult.Hate.Score, Is.EqualTo(hateScore)); - [Test] - public void ModerationCategoriesWithViolenceGraphicWorks() - { - ModerationCategories moderationCategories = OpenAIModerationsModelFactory.ModerationCategories(violenceGraphic: true); - - Assert.That(moderationCategories.Hate, Is.False); - Assert.That(moderationCategories.HateThreatening, Is.False); - Assert.That(moderationCategories.Harassment, Is.False); - Assert.That(moderationCategories.HarassmentThreatening, Is.False); - Assert.That(moderationCategories.SelfHarm, Is.False); - Assert.That(moderationCategories.SelfHarmIntent, Is.False); - Assert.That(moderationCategories.SelfHarmInstructions, Is.False); - Assert.That(moderationCategories.Sexual, Is.False); - Assert.That(moderationCategories.SexualMinors, Is.False); - Assert.That(moderationCategories.Violence, Is.False); - Assert.That(moderationCategories.ViolenceGraphic, Is.True); + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithNoPropertiesWorks() + public void ModerationResultWithHateThreateningWorks() { - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); - } + float hateThreateningScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, hateThreateningScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(hateThreatening: category); - [Test] - public void ModerationCategoryScoresWithHateWorks() - { - float hate = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(hate: hate); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(hate)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); - } + Assert.That(moderationResult.HateThreatening.Flagged, Is.True); + Assert.That(moderationResult.HateThreatening.Score, Is.EqualTo(hateThreateningScore)); - [Test] - public void ModerationCategoryScoresWithHateThreateningWorks() - { - float hateThreatening = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(hateThreatening: hateThreatening); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(hateThreatening)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithHarassmentWorks() + public void ModerationResultWithHarassmentWorks() { - float harassment = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(harassment: harassment); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(harassment)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float harassmentScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, harassmentScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(harassment: category); + + Assert.That(moderationResult.Harassment.Flagged, Is.True); + Assert.That(moderationResult.Harassment.Score, Is.EqualTo(harassmentScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithHarassmentThreateningWorks() + public void ModerationResultWithHarassmentThreateningWorks() { - float harassmentThreatening = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(harassmentThreatening: harassmentThreatening); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(harassmentThreatening)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float harassmentThreateningScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, harassmentThreateningScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(harassmentThreatening: category); + + Assert.That(moderationResult.HarassmentThreatening.Flagged, Is.True); + Assert.That(moderationResult.HarassmentThreatening.Score, Is.EqualTo(harassmentThreateningScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithSelfHarmWorks() + public void ModerationResultWithSelfHarmWorks() { - float selfHarm = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(selfHarm: selfHarm); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(selfHarm)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float selfHarmScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, selfHarmScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(selfHarm: category); + + Assert.That(moderationResult.SelfHarm.Flagged, Is.True); + Assert.That(moderationResult.SelfHarm.Score, Is.EqualTo(selfHarmScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithSelfHarmIntentWorks() + public void ModerationResultWithSelfHarmIntentWorks() { - float selfHarmIntent = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(selfHarmIntent: selfHarmIntent); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(selfHarmIntent)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float selfHarmIntentScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, selfHarmIntentScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(selfHarmIntent: category); + + Assert.That(moderationResult.SelfHarmIntent.Flagged, Is.True); + Assert.That(moderationResult.SelfHarmIntent.Score, Is.EqualTo(selfHarmIntentScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithSelfHarmInstructionWorks() + public void ModerationResultWithSelfHarmInstructionWorks() { - float selfHarmInstructions = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(selfHarmInstructions: selfHarmInstructions); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(selfHarmInstructions)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float selfHarmInstructionsScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, selfHarmInstructionsScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(selfHarmInstructions: category); + + Assert.That(moderationResult.SelfHarmInstructions.Flagged, Is.True); + Assert.That(moderationResult.SelfHarmInstructions.Score, Is.EqualTo(selfHarmInstructionsScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithSexualWorks() + public void ModerationResultWithSexualWorks() { - float sexual = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(sexual: sexual); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(sexual)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float sexualScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, sexualScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(sexual: category); + + Assert.That(moderationResult.Sexual.Flagged, Is.True); + Assert.That(moderationResult.Sexual.Score, Is.EqualTo(sexualScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithSexualMinorsWorks() + public void ModerationResultWithSexualMinorsWorks() { - float sexualMinors = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(sexualMinors: sexualMinors); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(sexualMinors)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float sexualMinorsScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, sexualMinorsScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(sexualMinors: category); + + Assert.That(moderationResult.SexualMinors.Flagged, Is.True); + Assert.That(moderationResult.SexualMinors.Score, Is.EqualTo(sexualMinorsScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithViolenceWorks() + public void ModerationResultWithViolenceWorks() { - float violence = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(violence: violence); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(violence)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(0f)); + float violenceScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, violenceScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(violence: category); + + Assert.That(moderationResult.Violence.Flagged, Is.True); + Assert.That(moderationResult.Violence.Score, Is.EqualTo(violenceScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.ViolenceGraphic, Is.Null); } [Test] - public void ModerationCategoryScoresWithViolenceGraphicWorks() + public void ModerationResultWithViolenceGraphicWorks() { - float violenceGraphic = 0.85f; - ModerationCategoryScores moderationCategoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(violenceGraphic: violenceGraphic); - - Assert.That(moderationCategoryScores.Hate, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HateThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Harassment, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.HarassmentThreatening, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarm, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmIntent, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SelfHarmInstructions, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Sexual, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.SexualMinors, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.Violence, Is.EqualTo(0f)); - Assert.That(moderationCategoryScores.ViolenceGraphic, Is.EqualTo(violenceGraphic)); + float violenceGraphicScore = 0.85f; + ModerationCategory category = OpenAIModerationsModelFactory.ModerationCategory(true, violenceGraphicScore); + ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(violenceGraphic: category); + + Assert.That(moderationResult.ViolenceGraphic.Flagged, Is.True); + Assert.That(moderationResult.ViolenceGraphic.Score, Is.EqualTo(violenceGraphicScore)); + + Assert.That(moderationResult.Flagged, Is.False); + Assert.That(moderationResult.Hate, Is.Null); + Assert.That(moderationResult.HateThreatening, Is.Null); + Assert.That(moderationResult.Harassment, Is.Null); + Assert.That(moderationResult.HarassmentThreatening, Is.Null); + Assert.That(moderationResult.SelfHarm, Is.Null); + Assert.That(moderationResult.SelfHarmIntent, Is.Null); + Assert.That(moderationResult.SelfHarmInstructions, Is.Null); + Assert.That(moderationResult.Sexual, Is.Null); + Assert.That(moderationResult.SexualMinors, Is.Null); + Assert.That(moderationResult.Violence, Is.Null); } [Test] - public void ModerationCollectionWithNoPropertiesWorks() + public void ModerationResultCollectionWithNoPropertiesWorks() { - ModerationCollection moderationCollection = OpenAIModerationsModelFactory.ModerationCollection(); + ModerationResultCollection moderationCollection = OpenAIModerationsModelFactory.ModerationResultCollection(); Assert.That(moderationCollection.Id, Is.Null); Assert.That(moderationCollection.Model, Is.Null); @@ -465,10 +321,10 @@ public void ModerationCollectionWithNoPropertiesWorks() } [Test] - public void ModerationCollectionWithIdWorks() + public void ModerationResultCollectionWithIdWorks() { string id = "moderationId"; - ModerationCollection moderationCollection = OpenAIModerationsModelFactory.ModerationCollection(id: id); + ModerationResultCollection moderationCollection = OpenAIModerationsModelFactory.ModerationResultCollection(id: id); Assert.That(moderationCollection.Id, Is.EqualTo(id)); Assert.That(moderationCollection.Model, Is.Null); @@ -476,10 +332,10 @@ public void ModerationCollectionWithIdWorks() } [Test] - public void ModerationCollectionWithModelWorks() + public void ModerationResultCollectionWithModelWorks() { string model = "supermodel"; - ModerationCollection moderationCollection = OpenAIModerationsModelFactory.ModerationCollection(model: model); + ModerationResultCollection moderationCollection = OpenAIModerationsModelFactory.ModerationResultCollection(model: model); Assert.That(moderationCollection.Id, Is.Null); Assert.That(moderationCollection.Model, Is.EqualTo(model)); @@ -487,58 +343,16 @@ public void ModerationCollectionWithModelWorks() } [Test] - public void ModerationCollectionWithItemsWorks() + public void ModerationResultCollectionWithItemsWorks() { IEnumerable items = [ OpenAIModerationsModelFactory.ModerationResult(flagged: true), OpenAIModerationsModelFactory.ModerationResult(flagged: false) ]; - ModerationCollection moderationCollection = OpenAIModerationsModelFactory.ModerationCollection(items: items); + ModerationResultCollection moderationCollection = OpenAIModerationsModelFactory.ModerationResultCollection(items: items); Assert.That(moderationCollection.Id, Is.Null); Assert.That(moderationCollection.Model, Is.Null); Assert.That(moderationCollection.SequenceEqual(items), Is.True); } - - [Test] - public void ModerationResultWithNoPropertiesWorks() - { - ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(); - - Assert.That(moderationResult.Flagged, Is.False); - Assert.That(moderationResult.Categories, Is.Null); - Assert.That(moderationResult.CategoryScores, Is.Null); - } - - [Test] - public void ModerationResultWithFlaggedWorks() - { - ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(flagged: true); - - Assert.That(moderationResult.Flagged, Is.True); - Assert.That(moderationResult.Categories, Is.Null); - Assert.That(moderationResult.CategoryScores, Is.Null); - } - - [Test] - public void ModerationResultWithCategoriesWorks() - { - ModerationCategories categories = OpenAIModerationsModelFactory.ModerationCategories(hate: true); - ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(categories: categories); - - Assert.That(moderationResult.Flagged, Is.False); - Assert.That(moderationResult.Categories, Is.EqualTo(categories)); - Assert.That(moderationResult.CategoryScores, Is.Null); - } - - [Test] - public void ModerationResultWithCategoryScoresWorks() - { - ModerationCategoryScores categoryScores = OpenAIModerationsModelFactory.ModerationCategoryScores(hate: 0.85f); - ModerationResult moderationResult = OpenAIModerationsModelFactory.ModerationResult(categoryScores: categoryScores); - - Assert.That(moderationResult.Flagged, Is.False); - Assert.That(moderationResult.Categories, Is.Null); - Assert.That(moderationResult.CategoryScores, Is.EqualTo(categoryScores)); - } }